From 09d7198004aa19358dad13e7bf8bd91a0e059911 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 7 Mar 2022 11:21:55 +0300 Subject: [PATCH 1/9] Completed. --- Lesson_5/task_1.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Lesson_5/task_1.py diff --git a/Lesson_5/task_1.py b/Lesson_5/task_1.py new file mode 100644 index 0000000..b8f1585 --- /dev/null +++ b/Lesson_5/task_1.py @@ -0,0 +1,10 @@ +# Создать программный файл в текстовом формате, +# записать в него построчно данные, вводимые пользователем. +# Об окончании ввода данных будет свидетельствовать пустая строка. + +with open('text.txt', 'w', encoding='utf-8') as f: + while True: + mstr = input('Please enter any text: ') + if not mstr: + break + print(mstr, file=f) From b56c6b9a4f915e4a35984b4f92e7ebb99f57be84 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 7 Mar 2022 12:03:50 +0300 Subject: [PATCH 2/9] Almost completed (there are some shortcomings) --- Lesson_5/task_2.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Lesson_5/task_2.py diff --git a/Lesson_5/task_2.py b/Lesson_5/task_2.py new file mode 100644 index 0000000..842bd76 --- /dev/null +++ b/Lesson_5/task_2.py @@ -0,0 +1,15 @@ +# Создать текстовый файл (не программно), сохранить в нём несколько строк, +# выполнить подсчёт строк и слов в каждой строке. + +f = open('text.txt', 'r', encoding='utf-8') +print(f.read()) + +with open('text.txt', 'r', encoding='utf-8') as f: + lines = 0 + words = 0 + for line in f: + lines += line.count('\n') + words += len(line.split()) + print(f'{words} words in each line.') + print(f'{lines} lines in the text document.') + From 254d381f119d1298a6beef4bf052c224377cc12b Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 7 Mar 2022 12:51:01 +0300 Subject: [PATCH 3/9] Looks like everything is ok. Completed. --- Lesson_5/task_3.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Lesson_5/task_3.py diff --git a/Lesson_5/task_3.py b/Lesson_5/task_3.py new file mode 100644 index 0000000..d2ee2cd --- /dev/null +++ b/Lesson_5/task_3.py @@ -0,0 +1,18 @@ +# Создать текстовый файл (не программно). Построчно записать фамилии +# сотрудников и величину их окладов (не менее 10 строк). +# Определить, кто из сотрудников имеет оклад менее 20 тысяч, +# вывести фамилии этих сотрудников. +# Выполнить подсчёт средней величины дохода сотрудников. +# Пример файла: Иванов 23543.12, Петров 13749.32. + +with open('text_3.txt', 'r') as f: + salary = [] + min_sal = [] + mlist = f.read().split('\n') + for i in mlist: + i = i.split() + if float(i[1]) < 20000: + min_sal.append(i[0]) + salary.append(i[1]) +print(f'The salary less than 20000 have: {min_sal}') +print(f'The average salary is: {sum(map(float, salary)) / len(salary)}') From 3d98b3399357622c75e651ee20082c71f3e25f5d Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 7 Mar 2022 14:14:13 +0300 Subject: [PATCH 4/9] Something wrong. Still can't find the problem. --- Lesson_5/task_4.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Lesson_5/task_4.py diff --git a/Lesson_5/task_4.py b/Lesson_5/task_4.py new file mode 100644 index 0000000..53583e7 --- /dev/null +++ b/Lesson_5/task_4.py @@ -0,0 +1,31 @@ +# Создать (не программно) текстовый файл со следующим содержимым: +# One — 1 +# Two — 2 +# Three — 3 +# Four — 4 +# Напишите программу, открывающую файл на чтение и считывающую +# построчно данные. При этом английские числительные должны +# заменяться на русские. Новый блок строк должен +# записываться в новый текстовый файл. + +# from googletrans import Translator +# +# with open('text_4.txt', 'r', encoding='utf-8') as f: +# if f.mode == 'r': +# content = f.read() +# print(content) +# +# translator = Translator() +# result = translator.translate(content, dest='ru') +# print(result.text) + +mdict = {'One': 'Один', 'Two': 'Два', 'Three': 'Три', 'Four': 'Четыре'} +new_list = [] +with open('text_4.txt', 'r') as f: + for i in f: + i = i.split('-', 1) + new_list.append(mdict[i[0]] + ' ' + i[1]) + print(new_list) + +with open('text_4_1.txt', 'w') as f_new: + f_new.writelines(new_list) From 7527a0372a2b0304d524c259ebe494345e7f8101 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 7 Mar 2022 14:50:13 +0300 Subject: [PATCH 5/9] Something wrong. Three different attempts and still can't figure out what's wrong --- Lesson_5/task_4.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Lesson_5/task_4.py b/Lesson_5/task_4.py index 53583e7..7d02058 100644 --- a/Lesson_5/task_4.py +++ b/Lesson_5/task_4.py @@ -20,12 +20,23 @@ # print(result.text) mdict = {'One': 'Один', 'Two': 'Два', 'Three': 'Три', 'Four': 'Четыре'} + new_list = [] -with open('text_4.txt', 'r') as f: +with open('text_4.txt', 'r', encoding='utf-8') as f: for i in f: i = i.split('-', 1) new_list.append(mdict[i[0]] + ' ' + i[1]) print(new_list) with open('text_4_1.txt', 'w') as f_new: - f_new.writelines(new_list) + f_new.writelines(new_list) + +# mdict = {'One': 'Один', 'Two': 'Два', 'Three': 'Три', 'Four': 'Четыре'} +# +# new_list = [] +# with open('text_4.txt', 'r', encoding='utf-8') as f: +# with open('text_4_1.txt', 'w', encoding='utf-8') as f2: +# for line in f: +# el, *num = line.split() +# ru = mdict[el] +# f2.write(' '.join([ru] + num) + '\n') From 59d4a0838705295d0c8a2640a605d6ba6c3204c2 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 7 Mar 2022 15:11:46 +0300 Subject: [PATCH 6/9] Completed. --- Lesson_5/task_5.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Lesson_5/task_5.py diff --git a/Lesson_5/task_5.py b/Lesson_5/task_5.py new file mode 100644 index 0000000..eed3baa --- /dev/null +++ b/Lesson_5/task_5.py @@ -0,0 +1,19 @@ +# Создать (программно) текстовый файл, +# записать в него программно набор чисел, +# разделённых пробелами. Программа должна подсчитывать +# сумму чисел в файле и выводить её на экран. + +def msum(): + try: + with open('file_5.txt', 'w') as f: + line = input('Please enter numbers via space: ') + f.writelines(line) + my_numb = line.split() + print(sum(map(int, my_numb))) + except IOError: + print('I/O Error') + except ValueError: + print('Incorrect value. I/O Error') + + +msum() From bb1b2f775ca929217f699f6d3ff43e9932087e23 Mon Sep 17 00:00:00 2001 From: Pavel Date: Mon, 7 Mar 2022 15:13:20 +0300 Subject: [PATCH 7/9] Something wrong. Three different attempts and still can't figure out what's wrong. Added text files for tasks 1,3 and 4. --- Lesson_5/task_4.py | 2 +- Lesson_5/text.txt | 6 ++++++ Lesson_5/text_3.txt | 12 ++++++++++++ Lesson_5/text_4.txt | 4 ++++ Lesson_5/text_4_1.txt | 0 5 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 Lesson_5/text.txt create mode 100644 Lesson_5/text_3.txt create mode 100644 Lesson_5/text_4.txt create mode 100644 Lesson_5/text_4_1.txt diff --git a/Lesson_5/task_4.py b/Lesson_5/task_4.py index 7d02058..ab46ad5 100644 --- a/Lesson_5/task_4.py +++ b/Lesson_5/task_4.py @@ -24,7 +24,7 @@ new_list = [] with open('text_4.txt', 'r', encoding='utf-8') as f: for i in f: - i = i.split('-', 1) + i = i.split(' ', 1) new_list.append(mdict[i[0]] + ' ' + i[1]) print(new_list) diff --git a/Lesson_5/text.txt b/Lesson_5/text.txt new file mode 100644 index 0000000..528bb16 --- /dev/null +++ b/Lesson_5/text.txt @@ -0,0 +1,6 @@ +Какой-то текст написанный заранее и он не содержит никакой информации. +Какой-то текст написанный заранее и он не содержит никакой информации. +Какой-то текст написанный заранее и он не содержит никакой информации. +Какой-то текст написанный заранее и он не содержит никакой информации. +Какой-то текст написанный заранее и он не содержит никакой информации. +Какой-то текст написанный заранее и он не содержит никакой информации. diff --git a/Lesson_5/text_3.txt b/Lesson_5/text_3.txt new file mode 100644 index 0000000..568b5d9 --- /dev/null +++ b/Lesson_5/text_3.txt @@ -0,0 +1,12 @@ +Иванов 23543.12 +Петров 13749.32 +Сидоров 9845.23 +Быков 25343.12 +Румянцева 17449.32 +Сапожников 19800.23 +Усыч 28543.12 +Камнев 23749.32 +Алабина 18345.23 +Седов 22353.12 +Кириллов 13749.32 +Семенов 7845.23 \ No newline at end of file diff --git a/Lesson_5/text_4.txt b/Lesson_5/text_4.txt new file mode 100644 index 0000000..cd6742c --- /dev/null +++ b/Lesson_5/text_4.txt @@ -0,0 +1,4 @@ +one-1 +two-2 +three-3 +four-4 \ No newline at end of file diff --git a/Lesson_5/text_4_1.txt b/Lesson_5/text_4_1.txt new file mode 100644 index 0000000..e69de29 From 7ab50e060b6204ab60f99d95b61ea482c6a26103 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 8 Mar 2022 17:47:01 +0300 Subject: [PATCH 8/9] It seems to work (however, there is some misunderstanding why the code gave an error at some points). --- Lesson_5/file_6.txt | 4 ++++ Lesson_5/task_6.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 Lesson_5/file_6.txt create mode 100644 Lesson_5/task_6.py diff --git a/Lesson_5/file_6.txt b/Lesson_5/file_6.txt new file mode 100644 index 0000000..a5f197f --- /dev/null +++ b/Lesson_5/file_6.txt @@ -0,0 +1,4 @@ +Informatics: 100(л) 50(пр) 20(лаб) +Physics: 30(л) - 10(лаб) +Physical: - 30(пр) - +Literature: 90(л) 50(пр) - \ No newline at end of file diff --git a/Lesson_5/task_6.py b/Lesson_5/task_6.py new file mode 100644 index 0000000..771502f --- /dev/null +++ b/Lesson_5/task_6.py @@ -0,0 +1,36 @@ +# Сформировать (не программно) текстовый файл. +# В нём каждая строка должна описывать учебный предмет и +# наличие лекционных, практических и лабораторных занятий +# по предмету. Сюда должно входить и количество занятий. +# Необязательно, чтобы для каждого предмета были все типы занятий. +# Сформировать словарь, содержащий название предмета и +# общее количество занятий по нему. Вывести его на экран. +# Примеры строк файла: Информатика: 100(л) 50(пр) 20(лаб). +# Физика: 30(л) — 10(лаб) +# Физкультура: — 30(пр) — +# Пример словаря: {“Информатика”: 170, “Физика”: 40, “Физкультура”: 30} + +# d = dict() +# +# with open('file_6.txt', 'r', encoding='utf-8') as f: +# for line in f: +# name, rest = line.split(':') +# rest = rest.split() +# num = 0 +# for part in rest: +# if "-" in part: +# continue +# nums, type = part.split('(') +# num += int(nums) +# d[name] = num +# print(d) + +subj = {} +with open('file_6.txt', 'r', encoding='utf-8') as f: + lines = f.readlines() + # print(lines) +for line in lines: + data = line.replace('(', ' ').split() + # print(data) + subj[data[0][:-1]] = sum(int(i) for i in data if i.isdigit()) +print(subj) From c5382c45d8756f7864c736de118e9a7b023a7fa4 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 8 Mar 2022 18:34:00 +0300 Subject: [PATCH 9/9] Seems to be completed. --- Lesson_5/file_7.json | 1 + Lesson_5/file_7.txt | 4 ++++ Lesson_5/task_7.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 Lesson_5/file_7.json create mode 100644 Lesson_5/file_7.txt create mode 100644 Lesson_5/task_7.py diff --git a/Lesson_5/file_7.json b/Lesson_5/file_7.json new file mode 100644 index 0000000..4fa072d --- /dev/null +++ b/Lesson_5/file_7.json @@ -0,0 +1 @@ +{"Firm_1": 5000, "Firm_2": 50000, "Firm_3": 5000, "Firm_4": -150000} \ No newline at end of file diff --git a/Lesson_5/file_7.txt b/Lesson_5/file_7.txt new file mode 100644 index 0000000..0d68710 --- /dev/null +++ b/Lesson_5/file_7.txt @@ -0,0 +1,4 @@ +Firm_1 АО 10000 5000 +Firm_2 ЗАО 200000 150000 +Firm_3 ООО 750000 745000 +Firm_4 ПАO 500000 650000 diff --git a/Lesson_5/task_7.py b/Lesson_5/task_7.py new file mode 100644 index 0000000..fcc6f96 --- /dev/null +++ b/Lesson_5/task_7.py @@ -0,0 +1,44 @@ +# Создать вручную и заполнить несколькими строками текстовый файл, +# в котором каждая строка будет содержать данные о фирме: название, +# форма собственности, выручка, издержки. +# Пример строки файла: firm_1 ООО 10000 5000. +# +# Необходимо построчно прочитать файл, вычислить прибыль каждой компании, +# а также среднюю прибыль. Если фирма получила убытки, в расчёт средней +# прибыли её не включать. +# Далее реализовать список. Он должен содержать словарь с фирмами и их +# прибылями, а также словарь со средней прибылью. Если фирма получила убытки, +# также добавить её в словарь (со значением убытков). +# Пример списка: [{“firm_1”: 5000, “firm_2”: 3000, “firm_3”: 1000}, {“average_profit”: 2000}]. +# +# Итоговый список сохранить в виде json-объекта в соответствующий файл. +# Пример json-объекта: +# [{"firm_1": 5000, "firm_2": 3000, "firm_3": 1000}, {"average_profit": 2000}] +# Подсказка: использовать менеджер контекста. + +import json + +result = dict() +aver_profit = 0 +i = 0 + +with open('file_7.txt', 'r', encoding='utf-8') as f: + for line in f: + name, type, income, expenses = line.split() + # print(line) + profit = int(income) - int(expenses) + if profit >= 0: + aver_profit += profit + i += 1 + result[name] = profit +aver_profit /= i +print(f'Results of the companies: \n' + f'{result}') +print(f'Average profit is: \n' + f'{aver_profit}') + +with open('file_7.json', 'w', encoding='utf-8') as f: + json.dump(result, f) +json_str = json.dumps(result) +print(f'The json file has been created with the following content: \n ' + f' {json_str}')