mikhailemv

Untitled

Oct 13th, 2022
5,228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 25.72 KB | None | 0 0
  1. # 1.1
  2. vacancy = input('Введите название вакансии: ')
  3. description = input('Введите описание вакансии: ')
  4. experience = int(input('Введите требуемый опыт работы (лет): '))
  5. lower_bound = int(input('Введите нижнюю границу оклада вакансии: '))
  6. upper_bound = int(input('Введите верхнюю границу оклада вакансии: '))
  7. is_free_schedule = input('Есть ли свободный график (да / нет): ').lower() == 'да'
  8. is_premium = input('Является ли данная вакансия премиум-вакансией (да / нет): ').lower() == 'да'
  9.  
  10. print(vacancy, '({})'.format(type(vacancy).__name__))
  11. print(description, '({})'.format(type(description).__name__))
  12. print(experience, '({})'.format(type(experience).__name__))
  13. print(lower_bound, '({})'.format(type(lower_bound).__name__))
  14. print(upper_bound, '({})'.format(type(upper_bound).__name__))
  15. print(is_free_schedule, '({})'.format(type(is_free_schedule).__name__))
  16. print(is_premium, '({})'.format(type(is_premium).__name__))
  17.  
  18. # 1.2
  19. vacancy = input('Введите название вакансии: ')
  20. description = input('Введите описание вакансии: ')
  21. experience = int(input('Введите требуемый опыт работы (лет): '))
  22. lower_bound = int(input('Введите нижнюю границу оклада вакансии: '))
  23. upper_bound = int(input('Введите верхнюю границу оклада вакансии: '))
  24. free_schedule = input('Есть ли свободный график (да / нет): ')
  25. premium = input('Является ли данная вакансия премиум-вакансией (да / нет): ')
  26.  
  27. average_salary = (lower_bound + upper_bound) // 2
  28.  
  29. def get_suffix_by_age(count):
  30.     if count % 10 == 0 or 5 <= count % 10 <= 9 or 10 <= count % 100 <= 19:
  31.         return 'лет'
  32.     elif 2 <= count % 10 <= 4:
  33.         return 'года'
  34.     else:
  35.         return 'год'
  36.  
  37. def get_suffix_by_rubles(count):
  38.     if count % 10 == 0 or 5 <= count % 10 <= 9 or 10 <= count % 100 <= 19:
  39.         return 'рублей'
  40.     elif 2 <= count % 10 <= 4:
  41.         return 'рубля'
  42.     else:
  43.         return 'рубль'
  44.  
  45. print(vacancy)
  46. print('Описание: {}'.format(description))
  47. print('Требуемый опыт работы: {0} {1}'.format(experience,
  48.                                               get_suffix_by_age(experience)))
  49. print('Средний оклад: {0} {1}'.format(average_salary,
  50.                                       get_suffix_by_rubles(average_salary)))
  51. print('Свободный график: {}'.format(free_schedule))
  52. print('Премиум-вакансия: {}'.format(premium))
  53.  
  54. # 1.3
  55. vacancy = input('Введите название вакансии: ')
  56. while len(vacancy) < 1:
  57.     print('Данные некорректны, повторите ввод')
  58.     vacancy = input('Введите название вакансии: ')
  59.  
  60. description = input('Введите описание вакансии: ')
  61. while len(description) < 1:
  62.     print('Данные некорректны, повторите ввод')
  63.     description = input('Введите описание вакансии: ')
  64.  
  65. experience = input('Введите требуемый опыт работы (лет): ')
  66. while not experience.isdigit():
  67.     print('Данные некорректны, повторите ввод')
  68.     experience = input('Введите требуемый опыт работы (лет): ')
  69. else:
  70.     experience = int(experience)
  71.  
  72. lower_bound = input('Введите нижнюю границу оклада вакансии: ')
  73. while not lower_bound.isdigit():
  74.     print('Данные некорректны, повторите ввод')
  75.     lower_bound = input('Введите нижнюю границу оклада вакансии: ')
  76. else:
  77.     lower_bound = int(lower_bound)
  78.  
  79. upper_bound = input('Введите верхнюю границу оклада вакансии: ')
  80. while not upper_bound.isdigit():
  81.     print('Данные некорректны, повторите ввод')
  82.     upper_bound = input('Введите верхнюю границу оклада вакансии: ')
  83. else:
  84.     upper_bound = int(upper_bound)
  85.  
  86. free_schedule = input('Есть ли свободный график (да / нет): ')
  87. while not (free_schedule == 'да' or free_schedule == 'нет'):
  88.     print('Данные некорректны, повторите ввод')
  89.     free_schedule = input('Есть ли свободный график (да / нет): ')
  90.  
  91. premium = input('Является ли данная вакансия премиум-вакансией (да / нет): ')
  92. while not (premium == 'да' or premium == 'нет'):
  93.     print('Данные некорректны, повторите ввод')
  94.     premium = input('Является ли данная вакансия премиум-вакансией (да / нет): ')
  95.  
  96. average_salary = (lower_bound + upper_bound) // 2
  97.  
  98.  
  99. def get_suffix_by_age(count):
  100.     if count % 10 == 0 or 5 <= count % 10 <= 9 or 10 <= count % 100 <= 19:
  101.         return 'лет'
  102.     elif 2 <= count % 10 <= 4:
  103.         return 'года'
  104.     else:
  105.         return 'год'
  106.  
  107.  
  108. def get_suffix_by_rubles(count):
  109.     if count % 10 == 0 or 5 <= count % 10 <= 9 or 10 <= count % 100 <= 19:
  110.         return 'рублей'
  111.     elif 2 <= count % 10 <= 4:
  112.         return 'рубля'
  113.     else:
  114.         return 'рубль'
  115.  
  116.  
  117. print(vacancy)
  118. print('Описание: {}'.format(description))
  119. print('Требуемый опыт работы: {0} {1}'.format(experience,
  120.                                               get_suffix_by_age(experience)))
  121. print('Средний оклад: {0} {1}'.format(average_salary,
  122.                                       get_suffix_by_rubles(average_salary)))
  123. print('Свободный график: {}'.format(free_schedule))
  124. print('Премиум-вакансия: {}'.format(premium))
  125.  
  126. # 2.1
  127. import csv
  128.  
  129. csv_file = input()
  130.  
  131. with open(csv_file, 'r', encoding='utf-8') as f:
  132.     reader = csv.reader(f)
  133.     title = next(reader)
  134.     data, title[0] = [], 'name'
  135.     for line in reader:
  136.         if len(line) < len(title):
  137.             continue
  138.         is_correct_string = True
  139.         for check_line in line:
  140.             if len(check_line) == 0:
  141.                 is_correct_string = False
  142.                 break
  143.         if is_correct_string:
  144.             data.append(line)
  145.  
  146. print(title, data, sep='\n')
  147.  
  148. # 2.2
  149. import csv
  150. import re
  151.  
  152. csv_file = input()
  153.  
  154. with open(csv_file, 'r', encoding='utf-8') as f:
  155.     reader = csv.reader(f)
  156.     title = next(reader)
  157.     data, title[0] = [], 'name'
  158.     html_tags = re.compile(r'<[^>]+>')
  159.     for line in reader:
  160.         if len(line) < len(title):
  161.             continue
  162.         is_correct_string = True
  163.         for index, value in enumerate(line):
  164.             normal_string = re.sub(html_tags, '', value)\
  165.                 .replace('\n', ', ')\
  166.                 .replace('\r\n', ', ')
  167.             normal_string = ' '.join(normal_string.split())
  168.             line[index] = normal_string
  169.             if len(normal_string) == 0:
  170.                 is_correct_string = False
  171.                 break
  172.         if is_correct_string:
  173.             current_dict = {title[i]: line[i] for i in range(len(title))}
  174.             for key in current_dict.keys():
  175.                 print(f'{key}: {current_dict[key]}')
  176.             print()
  177.            
  178. # 2.3
  179. import csv
  180. import math
  181. import re
  182. from collections import Counter
  183. import numpy
  184.  
  185.  
  186. csv_file = input()
  187.  
  188.  
  189. def get_ruble_suffix(count) -> str:
  190.     if count % 10 == 0 or \
  191.             5 <= count % 10 <= 9 or \
  192.             10 <= count % 100 <= 19:
  193.         return 'рублей'
  194.     elif 2 <= count % 10 <= 4:
  195.         return 'рубля'
  196.     else:
  197.         return 'рубль'
  198.  
  199.  
  200. def get_vacancies_suffix(count: int) -> str:
  201.     if 11 <= count % 100 <= 19:
  202.         return "вакансий"
  203.     elif count % 10 == 0 or 5 <= count % 10 <= 9:
  204.         return "вакансий"
  205.     elif 2 <= count % 10 <= 4:
  206.         return "вакансии"
  207.     else:
  208.         return "вакансия"
  209.  
  210.  
  211. def get_times_suffix(count: int) -> str:
  212.     if 11 <= count % 100 <= 19:
  213.         return "раз"
  214.     elif 2 <= count % 10 <= 4:
  215.         return "раза"
  216.     else:
  217.         return "раз"
  218.  
  219.  
  220. def print_vacancies_by_salaries(list_vacancies: list, is_high_salary: bool):
  221.     list_vacancies = sorted(list_vacancies,
  222.                             key=lambda x: x['avg_salary'],
  223.                             reverse=is_high_salary)
  224.     print('Самые высокие зарплаты:' if is_high_salary else 'Самые низкие зарплаты:')
  225.     counter = 0
  226.     for index, value in enumerate(list_vacancies):
  227.         if value['salary_currency'] != 'RUR':
  228.             continue
  229.         if counter == 10:
  230.             break
  231.         counter += 1
  232.         print(
  233.             f'    {counter}) {value["name"]} в компании \"{value["employer_name"]}\" - {value["avg_salary"]} '
  234.             f'{get_ruble_suffix(value["avg_salary"])} (г. {value["area_name"]})')
  235.     print()
  236.  
  237.  
  238. def print_top_skills(list_vacancies: list):
  239.     new_list = []
  240.     for index, value in enumerate(list_vacancies):
  241.         for j, v in enumerate(value["key_skills"]):
  242.             new_list.append(v.strip())
  243.     counter = Counter(new_list).most_common()
  244.     dictionary = dict(counter)
  245.     print(f'Из {len(dictionary)} скиллов, самыми популярными являются:')
  246.     i = 0
  247.     for key, value in dictionary.items():
  248.         if i == 10:
  249.             break
  250.         i += 1
  251.         print(f'    {i}) {key} - упоминается {value} {get_times_suffix(value)}')
  252.     print()
  253.  
  254.  
  255. def print_cities_by_salaries(input_list: list):
  256.     list_vacancies = []
  257.     for vac in input_list:
  258.         if vac['salary_currency'] == 'RUR':
  259.             list_vacancies.append(vac)
  260.     list_vacancies = sorted(list_vacancies, key=lambda x: x["area_name"])
  261.     temp_list = []
  262.     counter = 0
  263.     dict_cicties = {}
  264.  
  265.     for i in range(len(list_vacancies) + 1):
  266.         if i == 0:
  267.             continue
  268.         if i != len(list_vacancies):
  269.             if i == len(list_vacancies) - 1:
  270.                 if counter > 0:
  271.                     dict_cicties[list_vacancies[i - 1]["area_name"]] = (math.floor(numpy.average(temp_list)), counter)
  272.                 else:
  273.                     dict_cicties[list_vacancies[i - 1]["area_name"]] = (list_vacancies[i - 1]["avg_salary"], counter)
  274.                 temp_list = []
  275.                 counter = 0
  276.             if list_vacancies[i - 1]["area_name"] == list_vacancies[i]["area_name"]:
  277.                 temp_list.append(float(list_vacancies[i - 1]["avg_salary"]))
  278.                 counter += 1
  279.             else:
  280.                 temp_list.append(float(list_vacancies[i - 1]["avg_salary"]))
  281.                 counter += 1
  282.                 if counter > 0:
  283.                     dict_cicties[list_vacancies[i - 1]["area_name"]] = (math.floor(numpy.average(temp_list)), counter)
  284.                 else:
  285.                     dict_cicties[list_vacancies[i - 1]["area_name"]] = (list_vacancies[i - 1]["avg_salary"], counter)
  286.                 temp_list = []
  287.                 counter = 0
  288.         else:
  289.             temp_list.append(float(list_vacancies[i - 1]["avg_salary"]))
  290.             counter += 1
  291.             if counter > 0:
  292.                 dict_cicties[list_vacancies[i - 1]["area_name"]] = (math.floor(numpy.average(temp_list)), counter)
  293.             else:
  294.                 dict_cicties[list_vacancies[i - 1]["area_name"]] = (list_vacancies[i - 1]["avg_salary"], counter)
  295.             temp_list = []
  296.             counter = 0
  297.  
  298.     big_cities = dict()
  299.     for key, value in dict_cicties.items():
  300.         if value[1] * 100 / len(list_vacancies) >= 0.9:
  301.             big_cities[key] = value
  302.  
  303.     sorted_tuple = sorted(big_cities.items(),
  304.                                key=lambda x: (x[1][0], x[0]),
  305.                                reverse=True)
  306.  
  307.     for i, v in enumerate(sorted_tuple):
  308.         try:
  309.             if sorted_tuple[i - 1][1][0] == sorted_tuple[i][1][0]:
  310.                 temp1, temp2 = sorted_tuple[i - 1], sorted_tuple[i]
  311.                 sorted_tuple[i - 1] = temp2
  312.                 sorted_tuple[i] = temp1
  313.         except:
  314.             pass
  315.  
  316.     print(f'Из {len(dict_cicties)} городов, самые высокие средние ЗП:')
  317.     index = 0
  318.     for key, value in sorted_tuple:
  319.         if index >= 10:
  320.             break
  321.         print(f'    {index + 1}) {key} - средняя зарплата {value[0]} {get_ruble_suffix(value[0])} '
  322.               f'({value[1]} {get_vacancies_suffix(value[1])})')
  323.         index += 1
  324.     print()
  325.  
  326.  
  327. def make_dictionary(titles, list_vac):
  328.     dictionary = {}
  329.     for index, title in enumerate(titles):
  330.         dictionary[title] = list_vac[index]
  331.     dictionary['avg_salary'] = math.floor((float(dictionary['salary_to']) + float(dictionary['salary_from'])) / 2)
  332.     return dictionary
  333.  
  334.  
  335. with open(csv_file, encoding='utf-8-sig') as f:
  336.     reader = csv.reader(f, delimiter=',')
  337.     vacancies_list, title = [], next(reader)
  338.     index_key_skills = title.index('key_skills')
  339.     index_currency = title.index('salary_currency')
  340.     html_tags = re.compile('<.*?>')
  341.     for vacancy in reader:
  342.         if vacancy[index_currency] != 'RUR':
  343.             continue
  344.         try:
  345.             vacancy.remove('')
  346.         except ValueError:
  347.             pass
  348.         for i in range(len(vacancy)):
  349.             if i != index_key_skills:
  350.                 vacancy[i] = re.sub(html_tags, '', vacancy[i]).strip()
  351.                 vacancy[i] = ' '.join(vacancy[i].split())
  352.             else:
  353.                 vacancy[i] = vacancy[i].strip()
  354.                 vacancy[i] = re.split("\n|\n\r", vacancy[i])
  355.  
  356.         if len(vacancy) == len(title):
  357.             vacancies_list.append(make_dictionary(title, vacancy))
  358.  
  359.  
  360. print_vacancies_by_salaries(vacancies_list, True)
  361. print_vacancies_by_salaries(vacancies_list, False)
  362. print_top_skills(vacancies_list)
  363. print_cities_by_salaries(vacancies_list)
  364.  
  365. # 3.1
  366. import csv
  367. import re
  368.  
  369. csv_file = input()
  370.  
  371.  
  372. def print_vacancies(russ_wildcard: dict, dictionary: dict):
  373.     print(f'Название: {dictionary["name"]}\n'
  374.           f'Описание: {dictionary["description"]}\n'
  375.           f'Навыки: {", ".join(dictionary["key_skills"])}\n'
  376.           f'Опыт работы: {dictionary["experience_id"]}\n'
  377.           f'Премиум-вакансия: {russ_wildcard[dictionary["premium"]]}\n'
  378.           f'Компания: {dictionary["employer_name"]}\n'
  379.           f'Нижняя граница вилки оклада: {dictionary["salary_from"]}\n'
  380.           f'Верхняя граница вилки оклада: {dictionary["salary_to"]}\n'
  381.           f'Оклад указан до вычета налогов: {russ_wildcard[dictionary["salary_gross"]]}\n'
  382.           f'Идентификатор валюты оклада: {dictionary["salary_currency"]}\n'
  383.           f'Название региона: {dictionary["area_name"]}\n'
  384.           f'Дата и время публикации вакансии: {dictionary["published_at"]}\n')
  385.  
  386.  
  387. def csv_filer(headlines: list, raw_list: list):
  388.     russ_wildcard = {'True': 'Да', 'False': 'Нет'}
  389.     index_key_skills = headlines.index('key_skills')
  390.     html_tags = re.compile('<.*?>')
  391.     for line in raw_list:
  392.         try:
  393.             line.remove('')
  394.         except ValueError:
  395.             pass
  396.         for index in range(len(line)):
  397.             if index != index_key_skills:
  398.                 line[index] = ' '.join(re.sub(html_tags, '', line[index])
  399.                                        .strip().split())
  400.             else:
  401.                 line[index] = list(map(lambda x: x.strip(), line[index].split('\n')))
  402.  
  403.         if len(line) == len(headlines):
  404.             dictionary = {headlines[i]: line[i] for i in range(len(headlines))}
  405.             print_vacancies(russ_wildcard=russ_wildcard,
  406.                             dictionary=dictionary)
  407.  
  408.  
  409. def csv_reader(csv_name: str):
  410.     with open(csv_name, encoding='utf-8-sig') as file:
  411.         file_reader = csv.reader(file, delimiter=',')
  412.         csv_filer(headlines=next(file_reader), raw_list=list(file_reader))
  413.  
  414.  
  415. csv_reader(csv_file)
  416.  
  417. # 3.2
  418. import csv
  419. import re
  420. from math import floor
  421.  
  422.  
  423. def formatter(old_dictionary: dict) -> dict:
  424.     formatting_dictionary = {
  425.         "experience_id": {
  426.             "noExperience": "Нет опыта",
  427.             "between1And3": "От 1 года до 3 лет",
  428.             "between3And6": "От 3 до 6 лет",
  429.             "moreThan6": "Более 6 лет" },
  430.         "premium": {
  431.             'True': 'Да',
  432.             'False': 'Нет' },
  433.         "salary_gross": {
  434.             'False': 'С вычетом налогов',
  435.             'True': 'Без вычета налогов' },
  436.         "salary_currency": {
  437.             "AZN": "Манаты",
  438.             "BYR": "Белорусские рубли",
  439.             "EUR": "Евро",
  440.             "GEL": "Грузинский лари",
  441.             "KGS": "Киргизский сом",
  442.             "KZT": "Тенге",
  443.             "RUR": "Рубли",
  444.             "UAH": "Гривны",
  445.             "USD": "Доллары",
  446.             "UZS": "Узбекский сум" }
  447.     }
  448.     old_dictionary['salary_all'] = ''
  449.     for key, value in old_dictionary.items():
  450.         if key == 'key_skills':
  451.             old_dictionary[key] = ", ".join(value)
  452.         if key == 'experience_id':
  453.             old_dictionary[key] = formatting_dictionary[key][value]
  454.         if key == 'premium':
  455.             old_dictionary[key] = formatting_dictionary[key][value]
  456.         if key == 'salary_from':
  457.             old_dictionary[key] = '{:,}'.format(floor(float(
  458.                 old_dictionary["salary_from"]))).replace(',', ' ')
  459.         if key == 'salary_to':
  460.             old_dictionary[key] = '{:,}'.format(floor(float(
  461.                 old_dictionary["salary_to"]))).replace(',', ' ')
  462.         if key == 'salary_gross':
  463.             old_dictionary[key] = formatting_dictionary[key][value]
  464.         if key == 'salary_currency':
  465.             old_dictionary['salary_all'] = f'{old_dictionary["salary_from"]} - ' \
  466.                                            f'{old_dictionary["salary_to"]} ' \
  467.                                            f'({formatting_dictionary[key][value]}) ' \
  468.                                            f'({old_dictionary["salary_gross"]})'
  469.         if key == 'published_at':
  470.             old_dictionary[key] = '.'.join(reversed(value[0:10].split('-')))
  471.  
  472.     return old_dictionary
  473.  
  474.  
  475. def print_vacancies(dictionary: dict):
  476.     print(f'Название: {dictionary["name"]}\n'
  477.           f'Описание: {dictionary["description"]}\n'
  478.           f'Навыки: {dictionary["key_skills"]}\n'
  479.           f'Опыт работы: {dictionary["experience_id"]}\n'
  480.           f'Премиум-вакансия: {dictionary["premium"]}\n'
  481.           f'Компания: {dictionary["employer_name"]}\n'
  482.           f'Оклад: {dictionary["salary_all"]}\n'
  483.           f'Название региона: {dictionary["area_name"]}\n'
  484.           f'Дата публикации вакансии: {dictionary["published_at"]}\n')
  485.  
  486.  
  487. def csv_filer(headlines: list, raw_list: list):
  488.     index_key_skills = headlines.index('key_skills')
  489.     html_tags = re.compile('<.*?>')
  490.     for line in raw_list:
  491.         try:
  492.             line.remove('')
  493.         except ValueError:
  494.             pass
  495.         for index in range(len(line)):
  496.             if index != index_key_skills:
  497.                 line[index] = ' '.join(re.sub(html_tags, '', line[index])
  498.                                        .strip().split())
  499.             else:
  500.                 line[index] = list(map(lambda x: x.strip(), line[index].split('\n')))
  501.  
  502.         if len(line) == len(headlines):
  503.             dictionary = {headlines[i]: line[i] for i in range(len(headlines))}
  504.             print_vacancies(dictionary=formatter(dictionary))
  505.  
  506.  
  507. def csv_reader(csv_name: str):
  508.     with open(csv_name, encoding='utf-8-sig') as file:
  509.         file_reader = csv.reader(file, delimiter=',')
  510.         csv_filer(headlines=next(file_reader), raw_list=list(file_reader))
  511.  
  512.  
  513. csv_file = input()
  514. csv_reader(csv_file)
  515.  
  516. # 3.3
  517. import csv
  518. import re
  519. import textwrap
  520. from prettytable import PrettyTable
  521. import os
  522.  
  523. dic_naming = {'name': 'Название', 'description': 'Описание', 'key_skills': 'Навыки', 'experience_id': 'Опыт работы',
  524.               'premium': 'Премиум-вакансия', 'employer_name': 'Компания', 'salary_from': 'Оклад',
  525.               'salary_to': 'Верхняя граница вилки оклада', 'salary_gross': 'Оклад указан до вычета налогов',
  526.               'salary_currency': 'Идентификатор валюты оклада', 'area_name': 'Название региона',
  527.               'published_at': 'Дата публикации вакансии'}
  528.  
  529. dic_naming_new = {'№': '№', 'name': 'Название', 'description': 'Описание', 'key_skills': 'Навыки',
  530.                   'experience_id': 'Опыт работы', 'premium': 'Премиум-вакансия', 'employer_name': 'Компания',
  531.                   'salary_from': 'Оклад               ', 'area_name': 'Название региона',
  532.                   'published_at': 'Дата публикации вакансии'}
  533.  
  534. dic_yer = {"noExperience": "Нет опыта", "between1And3": "От 1 года до 3 лет",
  535.            "between3And6": "От 3 до 6 лет", "moreThan6": "Более 6 лет"}
  536.  
  537. dic_val = {"AZN": "Манаты", "BYR": "Белорусские рубли", "EUR": "Евро", "GEL": "Грузинский лари",
  538.            "KGS": "Киргизский сом", "KZT": "Тенге", "RUR": "Рубли", "UAH": "Гривны", "USD": "Доллары",
  539.            "UZS": "Узбекский сум"}
  540.  
  541.  
  542. def get_clear_string(x):
  543.     return ' '.join(re.sub(r"<[^>]+>", '', x).split())
  544.  
  545.  
  546. def get_money_right_form(money_amount: int) -> str:
  547.     string = str(money_amount)
  548.     if '.' in string:
  549.         string = string[:-2]
  550.  
  551.     xst = ''
  552.     for i in range(len(string)):
  553.         xst = string[-3:] + ' ' + xst
  554.         string = string[:-3]
  555.  
  556.     return xst.strip()
  557.  
  558.  
  559. def get_data_right_form(string: str) -> str:
  560.     return f'{string[8:10]}.{string[5:7]}.{string[:4]}'
  561.  
  562.  
  563. def translator(string: str) -> str:
  564.     if string == "False":
  565.         return "Нет"
  566.     return "Да"
  567.  
  568.  
  569. def csv_filer() -> list:
  570.     vacancies_list = list()
  571.     for row in headlines:
  572.         dictionary = dict()
  573.         if (len(row) != len(reader)) or ('' in row): continue
  574.         for key, value in zip(reader, row):
  575.             if '\n' in value:
  576.                 div = [get_clear_string(el) for el in value.split('\n')]
  577.                 dictionary[key] = ','.join(div)
  578.             else:
  579.                 dictionary[key] = get_clear_string(value)
  580.         vacancies_list.append(dictionary)
  581.     return vacancies_list
  582.  
  583.  
  584. def csv_reader(csv_name: str) -> tuple:
  585.     with open(csv_name, encoding='utf-8-sig') as file:
  586.         readers = csv.reader(file)
  587.         real_reader = readers.__next__()
  588.         title = [row for row in readers]
  589.         return real_reader, title
  590.  
  591.  
  592. def formatter(row: dict) -> dict:
  593.     dictionary = row
  594.     dictionary['premium'] = translator(dictionary['premium'])
  595.     dictionary['salary_gross'] = translator(dictionary['salary_gross'])
  596.  
  597.     if dictionary['salary_gross'] == 'Да':
  598.         tax = 'Без вычета налогов'
  599.     else:
  600.         tax = 'С вычетом налогов'
  601.     dictionary['salary_from'] = f"{get_money_right_form(dictionary['salary_from'])} - " \
  602.                                 f"{get_money_right_form(dictionary['salary_to'])} " \
  603.                                 f"({dic_val[dictionary['salary_currency']]}) ({tax})"
  604.     dictionary['experience_id'] = dic_yer[dictionary['experience_id']]
  605.     dictionary['published_at'] = get_data_right_form(dictionary['published_at'])
  606.     del dictionary['salary_to'], dictionary['salary_currency'], dictionary['salary_gross']
  607.  
  608.     return dictionary
  609.  
  610.  
  611. def get_table_form(current_dictionary: dict, counter: int) -> list:
  612.     table_form_list = [str(counter + 1)]
  613.     for key, value in current_dictionary.items():
  614.         if key == 'key_skills':
  615.             if len(value) > 100:
  616.                 element = value[:100] + '...'
  617.             else:
  618.                 element = value
  619.             string = ''
  620.             for k in element.split(','):
  621.                 string += textwrap.fill(k, width=20)
  622.                 string += '\n'
  623.             table_form_list.append(string[:-1])
  624.         else:
  625.             if len(value) > 100:
  626.                 element = value[:100] + '...'
  627.             else:
  628.                 element = value
  629.             table_form_list.append(textwrap.fill(element, width=20))
  630.     return table_form_list
  631.  
  632.  
  633. def print_vacancies(vacancies_list: list):
  634.     table = PrettyTable()
  635.     table.field_names = dic_naming_new.values()
  636.     for i in range(len(vacancies_list)):
  637.         row = formatter(vacancies_list[i])
  638.         table.add_row(get_table_form(current_dictionary=dict(row),
  639.                                      counter=i))
  640.     table.align = "l"
  641.     table.hrules = True
  642.     print(table)
  643.  
  644.  
  645. if __name__ == '__main__':
  646.     file_name = input()
  647.     if os.stat(file_name).st_size == 0:
  648.         print('Пустой файл')
  649.     else:
  650.         reader, headlines = csv_reader(file_name)
  651.         data_vacancies = csv_filer()
  652.         if len(data_vacancies) == 0:
  653.             print('Нет данных')
  654.         else:
  655.             print_vacancies(data_vacancies)
Advertisement
Add Comment
Please, Sign In to add comment