Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 1.1
- vacancy = input('Введите название вакансии: ')
- description = input('Введите описание вакансии: ')
- experience = int(input('Введите требуемый опыт работы (лет): '))
- lower_bound = int(input('Введите нижнюю границу оклада вакансии: '))
- upper_bound = int(input('Введите верхнюю границу оклада вакансии: '))
- is_free_schedule = input('Есть ли свободный график (да / нет): ').lower() == 'да'
- is_premium = input('Является ли данная вакансия премиум-вакансией (да / нет): ').lower() == 'да'
- print(vacancy, '({})'.format(type(vacancy).__name__))
- print(description, '({})'.format(type(description).__name__))
- print(experience, '({})'.format(type(experience).__name__))
- print(lower_bound, '({})'.format(type(lower_bound).__name__))
- print(upper_bound, '({})'.format(type(upper_bound).__name__))
- print(is_free_schedule, '({})'.format(type(is_free_schedule).__name__))
- print(is_premium, '({})'.format(type(is_premium).__name__))
- # 1.2
- vacancy = input('Введите название вакансии: ')
- description = input('Введите описание вакансии: ')
- experience = int(input('Введите требуемый опыт работы (лет): '))
- lower_bound = int(input('Введите нижнюю границу оклада вакансии: '))
- upper_bound = int(input('Введите верхнюю границу оклада вакансии: '))
- free_schedule = input('Есть ли свободный график (да / нет): ')
- premium = input('Является ли данная вакансия премиум-вакансией (да / нет): ')
- average_salary = (lower_bound + upper_bound) // 2
- def get_suffix_by_age(count):
- if count % 10 == 0 or 5 <= count % 10 <= 9 or 10 <= count % 100 <= 19:
- return 'лет'
- elif 2 <= count % 10 <= 4:
- return 'года'
- else:
- return 'год'
- def get_suffix_by_rubles(count):
- if count % 10 == 0 or 5 <= count % 10 <= 9 or 10 <= count % 100 <= 19:
- return 'рублей'
- elif 2 <= count % 10 <= 4:
- return 'рубля'
- else:
- return 'рубль'
- print(vacancy)
- print('Описание: {}'.format(description))
- print('Требуемый опыт работы: {0} {1}'.format(experience,
- get_suffix_by_age(experience)))
- print('Средний оклад: {0} {1}'.format(average_salary,
- get_suffix_by_rubles(average_salary)))
- print('Свободный график: {}'.format(free_schedule))
- print('Премиум-вакансия: {}'.format(premium))
- # 1.3
- vacancy = input('Введите название вакансии: ')
- while len(vacancy) < 1:
- print('Данные некорректны, повторите ввод')
- vacancy = input('Введите название вакансии: ')
- description = input('Введите описание вакансии: ')
- while len(description) < 1:
- print('Данные некорректны, повторите ввод')
- description = input('Введите описание вакансии: ')
- experience = input('Введите требуемый опыт работы (лет): ')
- while not experience.isdigit():
- print('Данные некорректны, повторите ввод')
- experience = input('Введите требуемый опыт работы (лет): ')
- else:
- experience = int(experience)
- lower_bound = input('Введите нижнюю границу оклада вакансии: ')
- while not lower_bound.isdigit():
- print('Данные некорректны, повторите ввод')
- lower_bound = input('Введите нижнюю границу оклада вакансии: ')
- else:
- lower_bound = int(lower_bound)
- upper_bound = input('Введите верхнюю границу оклада вакансии: ')
- while not upper_bound.isdigit():
- print('Данные некорректны, повторите ввод')
- upper_bound = input('Введите верхнюю границу оклада вакансии: ')
- else:
- upper_bound = int(upper_bound)
- free_schedule = input('Есть ли свободный график (да / нет): ')
- while not (free_schedule == 'да' or free_schedule == 'нет'):
- print('Данные некорректны, повторите ввод')
- free_schedule = input('Есть ли свободный график (да / нет): ')
- premium = input('Является ли данная вакансия премиум-вакансией (да / нет): ')
- while not (premium == 'да' or premium == 'нет'):
- print('Данные некорректны, повторите ввод')
- premium = input('Является ли данная вакансия премиум-вакансией (да / нет): ')
- average_salary = (lower_bound + upper_bound) // 2
- def get_suffix_by_age(count):
- if count % 10 == 0 or 5 <= count % 10 <= 9 or 10 <= count % 100 <= 19:
- return 'лет'
- elif 2 <= count % 10 <= 4:
- return 'года'
- else:
- return 'год'
- def get_suffix_by_rubles(count):
- if count % 10 == 0 or 5 <= count % 10 <= 9 or 10 <= count % 100 <= 19:
- return 'рублей'
- elif 2 <= count % 10 <= 4:
- return 'рубля'
- else:
- return 'рубль'
- print(vacancy)
- print('Описание: {}'.format(description))
- print('Требуемый опыт работы: {0} {1}'.format(experience,
- get_suffix_by_age(experience)))
- print('Средний оклад: {0} {1}'.format(average_salary,
- get_suffix_by_rubles(average_salary)))
- print('Свободный график: {}'.format(free_schedule))
- print('Премиум-вакансия: {}'.format(premium))
- # 2.1
- import csv
- csv_file = input()
- with open(csv_file, 'r', encoding='utf-8') as f:
- reader = csv.reader(f)
- title = next(reader)
- data, title[0] = [], 'name'
- for line in reader:
- if len(line) < len(title):
- continue
- is_correct_string = True
- for check_line in line:
- if len(check_line) == 0:
- is_correct_string = False
- break
- if is_correct_string:
- data.append(line)
- print(title, data, sep='\n')
- # 2.2
- import csv
- import re
- csv_file = input()
- with open(csv_file, 'r', encoding='utf-8') as f:
- reader = csv.reader(f)
- title = next(reader)
- data, title[0] = [], 'name'
- html_tags = re.compile(r'<[^>]+>')
- for line in reader:
- if len(line) < len(title):
- continue
- is_correct_string = True
- for index, value in enumerate(line):
- normal_string = re.sub(html_tags, '', value)\
- .replace('\n', ', ')\
- .replace('\r\n', ', ')
- normal_string = ' '.join(normal_string.split())
- line[index] = normal_string
- if len(normal_string) == 0:
- is_correct_string = False
- break
- if is_correct_string:
- current_dict = {title[i]: line[i] for i in range(len(title))}
- for key in current_dict.keys():
- print(f'{key}: {current_dict[key]}')
- print()
- # 2.3
- import csv
- import math
- import re
- from collections import Counter
- import numpy
- csv_file = input()
- def get_ruble_suffix(count) -> str:
- if count % 10 == 0 or \
- 5 <= count % 10 <= 9 or \
- 10 <= count % 100 <= 19:
- return 'рублей'
- elif 2 <= count % 10 <= 4:
- return 'рубля'
- else:
- return 'рубль'
- def get_vacancies_suffix(count: int) -> str:
- if 11 <= count % 100 <= 19:
- return "вакансий"
- elif count % 10 == 0 or 5 <= count % 10 <= 9:
- return "вакансий"
- elif 2 <= count % 10 <= 4:
- return "вакансии"
- else:
- return "вакансия"
- def get_times_suffix(count: int) -> str:
- if 11 <= count % 100 <= 19:
- return "раз"
- elif 2 <= count % 10 <= 4:
- return "раза"
- else:
- return "раз"
- def print_vacancies_by_salaries(list_vacancies: list, is_high_salary: bool):
- list_vacancies = sorted(list_vacancies,
- key=lambda x: x['avg_salary'],
- reverse=is_high_salary)
- print('Самые высокие зарплаты:' if is_high_salary else 'Самые низкие зарплаты:')
- counter = 0
- for index, value in enumerate(list_vacancies):
- if value['salary_currency'] != 'RUR':
- continue
- if counter == 10:
- break
- counter += 1
- print(
- f' {counter}) {value["name"]} в компании \"{value["employer_name"]}\" - {value["avg_salary"]} '
- f'{get_ruble_suffix(value["avg_salary"])} (г. {value["area_name"]})')
- print()
- def print_top_skills(list_vacancies: list):
- new_list = []
- for index, value in enumerate(list_vacancies):
- for j, v in enumerate(value["key_skills"]):
- new_list.append(v.strip())
- counter = Counter(new_list).most_common()
- dictionary = dict(counter)
- print(f'Из {len(dictionary)} скиллов, самыми популярными являются:')
- i = 0
- for key, value in dictionary.items():
- if i == 10:
- break
- i += 1
- print(f' {i}) {key} - упоминается {value} {get_times_suffix(value)}')
- print()
- def print_cities_by_salaries(input_list: list):
- list_vacancies = []
- for vac in input_list:
- if vac['salary_currency'] == 'RUR':
- list_vacancies.append(vac)
- list_vacancies = sorted(list_vacancies, key=lambda x: x["area_name"])
- temp_list = []
- counter = 0
- dict_cicties = {}
- for i in range(len(list_vacancies) + 1):
- if i == 0:
- continue
- if i != len(list_vacancies):
- if i == len(list_vacancies) - 1:
- if counter > 0:
- dict_cicties[list_vacancies[i - 1]["area_name"]] = (math.floor(numpy.average(temp_list)), counter)
- else:
- dict_cicties[list_vacancies[i - 1]["area_name"]] = (list_vacancies[i - 1]["avg_salary"], counter)
- temp_list = []
- counter = 0
- if list_vacancies[i - 1]["area_name"] == list_vacancies[i]["area_name"]:
- temp_list.append(float(list_vacancies[i - 1]["avg_salary"]))
- counter += 1
- else:
- temp_list.append(float(list_vacancies[i - 1]["avg_salary"]))
- counter += 1
- if counter > 0:
- dict_cicties[list_vacancies[i - 1]["area_name"]] = (math.floor(numpy.average(temp_list)), counter)
- else:
- dict_cicties[list_vacancies[i - 1]["area_name"]] = (list_vacancies[i - 1]["avg_salary"], counter)
- temp_list = []
- counter = 0
- else:
- temp_list.append(float(list_vacancies[i - 1]["avg_salary"]))
- counter += 1
- if counter > 0:
- dict_cicties[list_vacancies[i - 1]["area_name"]] = (math.floor(numpy.average(temp_list)), counter)
- else:
- dict_cicties[list_vacancies[i - 1]["area_name"]] = (list_vacancies[i - 1]["avg_salary"], counter)
- temp_list = []
- counter = 0
- big_cities = dict()
- for key, value in dict_cicties.items():
- if value[1] * 100 / len(list_vacancies) >= 0.9:
- big_cities[key] = value
- sorted_tuple = sorted(big_cities.items(),
- key=lambda x: (x[1][0], x[0]),
- reverse=True)
- for i, v in enumerate(sorted_tuple):
- try:
- if sorted_tuple[i - 1][1][0] == sorted_tuple[i][1][0]:
- temp1, temp2 = sorted_tuple[i - 1], sorted_tuple[i]
- sorted_tuple[i - 1] = temp2
- sorted_tuple[i] = temp1
- except:
- pass
- print(f'Из {len(dict_cicties)} городов, самые высокие средние ЗП:')
- index = 0
- for key, value in sorted_tuple:
- if index >= 10:
- break
- print(f' {index + 1}) {key} - средняя зарплата {value[0]} {get_ruble_suffix(value[0])} '
- f'({value[1]} {get_vacancies_suffix(value[1])})')
- index += 1
- print()
- def make_dictionary(titles, list_vac):
- dictionary = {}
- for index, title in enumerate(titles):
- dictionary[title] = list_vac[index]
- dictionary['avg_salary'] = math.floor((float(dictionary['salary_to']) + float(dictionary['salary_from'])) / 2)
- return dictionary
- with open(csv_file, encoding='utf-8-sig') as f:
- reader = csv.reader(f, delimiter=',')
- vacancies_list, title = [], next(reader)
- index_key_skills = title.index('key_skills')
- index_currency = title.index('salary_currency')
- html_tags = re.compile('<.*?>')
- for vacancy in reader:
- if vacancy[index_currency] != 'RUR':
- continue
- try:
- vacancy.remove('')
- except ValueError:
- pass
- for i in range(len(vacancy)):
- if i != index_key_skills:
- vacancy[i] = re.sub(html_tags, '', vacancy[i]).strip()
- vacancy[i] = ' '.join(vacancy[i].split())
- else:
- vacancy[i] = vacancy[i].strip()
- vacancy[i] = re.split("\n|\n\r", vacancy[i])
- if len(vacancy) == len(title):
- vacancies_list.append(make_dictionary(title, vacancy))
- print_vacancies_by_salaries(vacancies_list, True)
- print_vacancies_by_salaries(vacancies_list, False)
- print_top_skills(vacancies_list)
- print_cities_by_salaries(vacancies_list)
- # 3.1
- import csv
- import re
- csv_file = input()
- def print_vacancies(russ_wildcard: dict, dictionary: dict):
- print(f'Название: {dictionary["name"]}\n'
- f'Описание: {dictionary["description"]}\n'
- f'Навыки: {", ".join(dictionary["key_skills"])}\n'
- f'Опыт работы: {dictionary["experience_id"]}\n'
- f'Премиум-вакансия: {russ_wildcard[dictionary["premium"]]}\n'
- f'Компания: {dictionary["employer_name"]}\n'
- f'Нижняя граница вилки оклада: {dictionary["salary_from"]}\n'
- f'Верхняя граница вилки оклада: {dictionary["salary_to"]}\n'
- f'Оклад указан до вычета налогов: {russ_wildcard[dictionary["salary_gross"]]}\n'
- f'Идентификатор валюты оклада: {dictionary["salary_currency"]}\n'
- f'Название региона: {dictionary["area_name"]}\n'
- f'Дата и время публикации вакансии: {dictionary["published_at"]}\n')
- def csv_filer(headlines: list, raw_list: list):
- russ_wildcard = {'True': 'Да', 'False': 'Нет'}
- index_key_skills = headlines.index('key_skills')
- html_tags = re.compile('<.*?>')
- for line in raw_list:
- try:
- line.remove('')
- except ValueError:
- pass
- for index in range(len(line)):
- if index != index_key_skills:
- line[index] = ' '.join(re.sub(html_tags, '', line[index])
- .strip().split())
- else:
- line[index] = list(map(lambda x: x.strip(), line[index].split('\n')))
- if len(line) == len(headlines):
- dictionary = {headlines[i]: line[i] for i in range(len(headlines))}
- print_vacancies(russ_wildcard=russ_wildcard,
- dictionary=dictionary)
- def csv_reader(csv_name: str):
- with open(csv_name, encoding='utf-8-sig') as file:
- file_reader = csv.reader(file, delimiter=',')
- csv_filer(headlines=next(file_reader), raw_list=list(file_reader))
- csv_reader(csv_file)
- # 3.2
- import csv
- import re
- from math import floor
- def formatter(old_dictionary: dict) -> dict:
- formatting_dictionary = {
- "experience_id": {
- "noExperience": "Нет опыта",
- "between1And3": "От 1 года до 3 лет",
- "between3And6": "От 3 до 6 лет",
- "moreThan6": "Более 6 лет" },
- "premium": {
- 'True': 'Да',
- 'False': 'Нет' },
- "salary_gross": {
- 'False': 'С вычетом налогов',
- 'True': 'Без вычета налогов' },
- "salary_currency": {
- "AZN": "Манаты",
- "BYR": "Белорусские рубли",
- "EUR": "Евро",
- "GEL": "Грузинский лари",
- "KGS": "Киргизский сом",
- "KZT": "Тенге",
- "RUR": "Рубли",
- "UAH": "Гривны",
- "USD": "Доллары",
- "UZS": "Узбекский сум" }
- }
- old_dictionary['salary_all'] = ''
- for key, value in old_dictionary.items():
- if key == 'key_skills':
- old_dictionary[key] = ", ".join(value)
- if key == 'experience_id':
- old_dictionary[key] = formatting_dictionary[key][value]
- if key == 'premium':
- old_dictionary[key] = formatting_dictionary[key][value]
- if key == 'salary_from':
- old_dictionary[key] = '{:,}'.format(floor(float(
- old_dictionary["salary_from"]))).replace(',', ' ')
- if key == 'salary_to':
- old_dictionary[key] = '{:,}'.format(floor(float(
- old_dictionary["salary_to"]))).replace(',', ' ')
- if key == 'salary_gross':
- old_dictionary[key] = formatting_dictionary[key][value]
- if key == 'salary_currency':
- old_dictionary['salary_all'] = f'{old_dictionary["salary_from"]} - ' \
- f'{old_dictionary["salary_to"]} ' \
- f'({formatting_dictionary[key][value]}) ' \
- f'({old_dictionary["salary_gross"]})'
- if key == 'published_at':
- old_dictionary[key] = '.'.join(reversed(value[0:10].split('-')))
- return old_dictionary
- def print_vacancies(dictionary: dict):
- print(f'Название: {dictionary["name"]}\n'
- f'Описание: {dictionary["description"]}\n'
- f'Навыки: {dictionary["key_skills"]}\n'
- f'Опыт работы: {dictionary["experience_id"]}\n'
- f'Премиум-вакансия: {dictionary["premium"]}\n'
- f'Компания: {dictionary["employer_name"]}\n'
- f'Оклад: {dictionary["salary_all"]}\n'
- f'Название региона: {dictionary["area_name"]}\n'
- f'Дата публикации вакансии: {dictionary["published_at"]}\n')
- def csv_filer(headlines: list, raw_list: list):
- index_key_skills = headlines.index('key_skills')
- html_tags = re.compile('<.*?>')
- for line in raw_list:
- try:
- line.remove('')
- except ValueError:
- pass
- for index in range(len(line)):
- if index != index_key_skills:
- line[index] = ' '.join(re.sub(html_tags, '', line[index])
- .strip().split())
- else:
- line[index] = list(map(lambda x: x.strip(), line[index].split('\n')))
- if len(line) == len(headlines):
- dictionary = {headlines[i]: line[i] for i in range(len(headlines))}
- print_vacancies(dictionary=formatter(dictionary))
- def csv_reader(csv_name: str):
- with open(csv_name, encoding='utf-8-sig') as file:
- file_reader = csv.reader(file, delimiter=',')
- csv_filer(headlines=next(file_reader), raw_list=list(file_reader))
- csv_file = input()
- csv_reader(csv_file)
- # 3.3
- import csv
- import re
- import textwrap
- from prettytable import PrettyTable
- import os
- dic_naming = {'name': 'Название', 'description': 'Описание', 'key_skills': 'Навыки', 'experience_id': 'Опыт работы',
- 'premium': 'Премиум-вакансия', 'employer_name': 'Компания', 'salary_from': 'Оклад',
- 'salary_to': 'Верхняя граница вилки оклада', 'salary_gross': 'Оклад указан до вычета налогов',
- 'salary_currency': 'Идентификатор валюты оклада', 'area_name': 'Название региона',
- 'published_at': 'Дата публикации вакансии'}
- dic_naming_new = {'№': '№', 'name': 'Название', 'description': 'Описание', 'key_skills': 'Навыки',
- 'experience_id': 'Опыт работы', 'premium': 'Премиум-вакансия', 'employer_name': 'Компания',
- 'salary_from': 'Оклад ', 'area_name': 'Название региона',
- 'published_at': 'Дата публикации вакансии'}
- dic_yer = {"noExperience": "Нет опыта", "between1And3": "От 1 года до 3 лет",
- "between3And6": "От 3 до 6 лет", "moreThan6": "Более 6 лет"}
- dic_val = {"AZN": "Манаты", "BYR": "Белорусские рубли", "EUR": "Евро", "GEL": "Грузинский лари",
- "KGS": "Киргизский сом", "KZT": "Тенге", "RUR": "Рубли", "UAH": "Гривны", "USD": "Доллары",
- "UZS": "Узбекский сум"}
- def get_clear_string(x):
- return ' '.join(re.sub(r"<[^>]+>", '', x).split())
- def get_money_right_form(money_amount: int) -> str:
- string = str(money_amount)
- if '.' in string:
- string = string[:-2]
- xst = ''
- for i in range(len(string)):
- xst = string[-3:] + ' ' + xst
- string = string[:-3]
- return xst.strip()
- def get_data_right_form(string: str) -> str:
- return f'{string[8:10]}.{string[5:7]}.{string[:4]}'
- def translator(string: str) -> str:
- if string == "False":
- return "Нет"
- return "Да"
- def csv_filer() -> list:
- vacancies_list = list()
- for row in headlines:
- dictionary = dict()
- if (len(row) != len(reader)) or ('' in row): continue
- for key, value in zip(reader, row):
- if '\n' in value:
- div = [get_clear_string(el) for el in value.split('\n')]
- dictionary[key] = ','.join(div)
- else:
- dictionary[key] = get_clear_string(value)
- vacancies_list.append(dictionary)
- return vacancies_list
- def csv_reader(csv_name: str) -> tuple:
- with open(csv_name, encoding='utf-8-sig') as file:
- readers = csv.reader(file)
- real_reader = readers.__next__()
- title = [row for row in readers]
- return real_reader, title
- def formatter(row: dict) -> dict:
- dictionary = row
- dictionary['premium'] = translator(dictionary['premium'])
- dictionary['salary_gross'] = translator(dictionary['salary_gross'])
- if dictionary['salary_gross'] == 'Да':
- tax = 'Без вычета налогов'
- else:
- tax = 'С вычетом налогов'
- dictionary['salary_from'] = f"{get_money_right_form(dictionary['salary_from'])} - " \
- f"{get_money_right_form(dictionary['salary_to'])} " \
- f"({dic_val[dictionary['salary_currency']]}) ({tax})"
- dictionary['experience_id'] = dic_yer[dictionary['experience_id']]
- dictionary['published_at'] = get_data_right_form(dictionary['published_at'])
- del dictionary['salary_to'], dictionary['salary_currency'], dictionary['salary_gross']
- return dictionary
- def get_table_form(current_dictionary: dict, counter: int) -> list:
- table_form_list = [str(counter + 1)]
- for key, value in current_dictionary.items():
- if key == 'key_skills':
- if len(value) > 100:
- element = value[:100] + '...'
- else:
- element = value
- string = ''
- for k in element.split(','):
- string += textwrap.fill(k, width=20)
- string += '\n'
- table_form_list.append(string[:-1])
- else:
- if len(value) > 100:
- element = value[:100] + '...'
- else:
- element = value
- table_form_list.append(textwrap.fill(element, width=20))
- return table_form_list
- def print_vacancies(vacancies_list: list):
- table = PrettyTable()
- table.field_names = dic_naming_new.values()
- for i in range(len(vacancies_list)):
- row = formatter(vacancies_list[i])
- table.add_row(get_table_form(current_dictionary=dict(row),
- counter=i))
- table.align = "l"
- table.hrules = True
- print(table)
- if __name__ == '__main__':
- file_name = input()
- if os.stat(file_name).st_size == 0:
- print('Пустой файл')
- else:
- reader, headlines = csv_reader(file_name)
- data_vacancies = csv_filer()
- if len(data_vacancies) == 0:
- print('Нет данных')
- else:
- print_vacancies(data_vacancies)
Advertisement
Add Comment
Please, Sign In to add comment