Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
9.3 kB
8
Indexable
Never
import csv
import re
import sys

import prettytable
from prettytable import PrettyTable

main_table = PrettyTable()
main_table_titles = []
COUNTER = 0
dic_naming = {
    "name": "Название",
    "description": "Описание",
    "key_skills": "Навыки",
    "experience_id": "Опыт работы",
    "premium": "Премиум-вакансия",
    "employer_name": "Компания",
    "salary_from": "Нижняя граница вилки оклада",
    "salary_to": "Верхняя граница вилки оклада",
    "salary_gross": "Оклад указан до вычета налогов",
    "salary_currency": "Идентификатор валюты оклада",
    "area_name": "Название региона",
    "published_at": "Дата и время публикации вакансии",
}

exp_naming = {
    "noExperience": "Нет опыта",
    "between1And3": "От 1 года до 3 лет",
    "between3And6": "От 3 до 6 лет",
    "moreThan6": "Более 6 лет"
}

currency_naming = {
    "AZN": "Манаты",
    "BYR": "Белорусские рубли",
    "EUR": "Евро",
    "GEL": "Грузинский лари",
    "KGS": "Киргизский сом",
    "KZT": "Тенге",
    "RUR": "Рубли",
    "UAH": "Гривны",
    "USD": "Доллары",
    "UZS": "Узбекский сум",
}

filter_dict = {
    "Название": lambda vac, req: vac["name"] == req[1],
    "Описание": lambda vac, req: vac["description"] == req[1],
    "Навыки": lambda vac, req: compare_skills(req, vac),
    "Опыт работы": lambda vac, req: exp_naming[vac["experience_id"]] == req[1],
    "Премиум-вакансия": lambda vac, req: tryConvertBoolToRussian(vac["premium"]) == req[1],
    "Компания": lambda vac, req: vac["employer_name"] == req[1],
    "Оклад": lambda vac, req: int(vac["salary_from"]) <= int(req[1]) <= int(vac["salary_to"]),
    "Идентификатор валюты оклада": lambda vac, req: currency_naming[vac["salary_currency"]] == req[1],
    "Название региона": lambda vac, req: vac["area_name"] == req[1],
    "Дата публикации вакансии": lambda vac, req: vac["published_at"][8:10] + "." + vac["published_at"][5:7] + "." \
                                              + vac["published_at"][:4] == req[1],
}


def compare_skills(requirement, vacancy):
    requirement[1] = requirement[1].split(', ')
    if isinstance(vacancy["key_skills"], list):
        for elem in requirement[1]:
            if elem not in vacancy["key_skills"]:
                return False
        return True
    return requirement[1][0] in [vacancy["key_skills"]]


def check_row(row: list, length: int) -> bool:
    if len(row) != length:
        return False
    for elem in row:
        if elem.strip() == "":
            return False
    return True


def csv_reader(file_name: str) -> tuple:
    with open(file_name, encoding='utf-8-sig') as file:
        file_reader = csv.reader(file, delimiter=",")
        try:
            first_row = file_reader.__next__()
        except BaseException:
            print("Пустой файл")
            sys.exit()
        length = len(first_row)
        filled_vacancies = []
        for row in file_reader:
            if check_row(row, length):
                filled_vacancies.append(row)
        if len(filled_vacancies) == 0:
            print('Нет данных')
            sys.exit()
        return first_row, filled_vacancies


def convert_list_to_dict(titles: list, vacancy: list) -> dict:
    return {titles[i]: vacancy[i] for i in range(len(titles))}


def csv_filer(filled_vacancies: list, titles: list) -> list:
    return [convert_list_to_dict(titles, vacancy) for vacancy in filled_vacancies]


def try_to_split(value: str):
    if value.__contains__("\n"):
        value = value.split("\n")
        value = [value[i].strip() for i in range(len(value))]
    return value


def process_value(value: str):
    new_value = re.sub(r'<[^>]*>', "", value)
    new_value = re.sub(" +", " ", new_value)
    new_value = re.sub(" ", " ", new_value)
    new_value = re.sub(" ", " ", new_value)
    if new_value[0] == " ":
        new_value = new_value[1:]
    if new_value[-1] == " ":
        new_value = new_value[:-1]
    new_value = re.sub(" +", " ", new_value)
    new_value = try_to_split(new_value)
    return new_value


def process_each_vacancy(vacancy: list) -> list:
    return [process_value(vacancy[i]) for i in range(len(vacancy))]


def get_processed_vacancy_list(vacancies: list) -> list:
    return [process_each_vacancy(vacancy) for vacancy in vacancies]


def tryConvertBoolToRussian(value: bool):
    if value == "True":
        return "Да"
    elif value == "False":
        return "Нет"
    return value


def process_salary(salary: str) -> str:
    result_salary = salary.strip()
    result_salary = result_salary.split(".")[0]
    return result_salary[:-3] + " " + result_salary[-3:] if len(result_salary) > 3 else result_salary


def cut_string(string: str) -> str:
    string = str(string)
    return f'{string[:100]}...' if len(string) > 100 else string


def format_key_skills(row_vacancy: dict) -> str:
    if isinstance(row_vacancy["key_skills"], list):
        return "\n".join(row_vacancy["key_skills"])
    else:
        return row_vacancy["key_skills"]


def format_salary_gross(row_vacancy: dict) -> str:
    result = f'{process_salary(row_vacancy["salary_from"])} - {process_salary(row_vacancy["salary_to"])} ' \
             f'({currency_naming[row_vacancy["salary_currency"]]}) '
    result += "(Без вычета налогов)" if row_vacancy["salary_gross"] == "True" else "(С вычетом налогов)"
    return result


def is_filtered_vacancy(requirement: str, vacancy: dict) -> bool:
    if requirement == '':
        return True
    if not requirement.__contains__(':'):
        print('Формат ввода некорректен')
        exit()
    requirement = requirement.split(':')
    requirement[1] = requirement[1][1:]
    if not filter_dict.__contains__(requirement[0]):
        print("Параметр поиска некорректен")
        exit()
    return filter_dict[requirement[0]](vacancy, requirement)


def formatter(row_vacancy: dict, count: int) -> dict:
    global COUNTER
    global main_table, main_table_titles
    formatted_dict = {"№": count, dic_naming["name"]: row_vacancy["name"],
                      dic_naming["description"]: row_vacancy["description"],
                      dic_naming["key_skills"]: format_key_skills(row_vacancy),
                      dic_naming["experience_id"]: exp_naming[row_vacancy["experience_id"]],
                      dic_naming["premium"]: tryConvertBoolToRussian(row_vacancy["premium"]),
                      dic_naming["employer_name"]: row_vacancy["employer_name"],
                      "Оклад": format_salary_gross(row_vacancy), dic_naming["area_name"]: row_vacancy["area_name"],
                      "Дата публикации вакансии": row_vacancy["published_at"][8:10] \
                                                  + "." + row_vacancy["published_at"][5:7] + "." \
                                                  + row_vacancy["published_at"][:4]}
    main_table.field_names = formatted_dict.keys()
    main_table_titles = formatted_dict.keys()
    main_table.max_width = 20
    new_row = [cut_string(formatted_dict[key]) for key in formatted_dict.keys()]
    main_table.add_row(new_row)
    COUNTER += 1
    return formatted_dict


def print_vacancies(data_vacancies: list, filter_parameters: str) -> None:
    global main_table_titles
    count = 1
    for vacancy in data_vacancies:
        if not is_filtered_vacancy(filter_parameters, vacancy):
            continue
        formatter(vacancy, count)
        count += 1


def get_input_values() -> dict:
    return {'file_name': input(), 'filter_parameters': input(), 'limits_input': input(), 'titles_input': input()}


def configure_table(inputs: dict) -> None:
    global main_table
    main_table.field_names = main_table_titles
    if inputs['limits_input']:
        limits = list(map(int, inputs['limits_input'].split(' ')))
        main_table.start = limits[0] - 1
        if len(limits) == 2:
            main_table.end = limits[1] - 1
    if inputs['titles_input']:
        titles = inputs['titles_input'].split(', ') + ['№']
        main_table.fields = titles
    main_table.valign = 't'
    main_table.align = 'l'
    main_table.hrules = prettytable.ALL


def main():
    inputs = get_input_values()
    list_result = csv_reader(inputs['file_name'])
    print_vacancies(csv_filer(get_processed_vacancy_list(list_result[1]), list_result[0]), inputs['filter_parameters'])
    if COUNTER == 0:
        print("Ничего не найдено")
        exit()
    configure_table(inputs)
    print(main_table.get_string())


main()