from config import plugins_config

class MyDict:
    """
    用于读取、存储、查找、删除teach内容
    """
    def __init__(self):
        # 初始化，读取文件
        self.d = {}
        self._read_dict()

    def add_kv(self, k: str, v: str):
        """
        添加键值对
        :param k: key
        :param v: calue
        :return: None
        """
        if self.find_k(k):
            return "我好像已经学过了呢……"
        else:
            self.d[k] = v
            self._save_dict()
            return "我学会啦~快夸我！"

    def delete_k(self, k: str) -> str:
        """
        删除键（以及相关的值）
        :param k: key
        :return: None
        """
        if self.find_k(k):
            self.d.pop(k)
            self._save_dict()
            return "我好像忘了什么……"
        else:
            return "我好像不记得我学过这个呢……"

    def find_k(self, k: str) -> str:
        """
        查找键
        :param k: key
        :return: value->str
        """
        if k in self.d:
            return self.d[k]
        else:
            return ""

    def _read_dict(self):
        """
        逐行读取文件至d
        :return: None
        """
        with open(plugins_config.data_url, 'r') as f:
            for line in f.readlines():
                line = line.strip()
                k = line.split(' ')[0]
                v = line.split(' ')[1]
                self.d[k] = v

    def _save_dict(self):
        """
        保存d至文件
        :return: None
        """
        with open(plugins_config.data_url, 'w+') as f:
            for k, v in self.d.items():
                f.write(str(k) + ' ' + str(v) + '\n')

md = MyDict()


import csv
import pymorphy2
from filters import filter_city_adj

with open('words2.csv', encoding="utf8") as csvfile1,  open('noun-adj.csv', 'w', newline='') as csvfile:
    reader = csv.reader(csvfile1, delimiter='/', quotechar='"')
    writer = csv.writer(
        csvfile, delimiter='|', quotechar='"', )

    d1 = {}
    morph = pymorphy2.MorphAnalyzer()

    for index, row in enumerate(reader):
        if index == 0:
            continue
        for i in range(len(row)):
            if morph.parse(row[i])[0].tag.POS == 'NOUN':
                if i > 0:
                    if morph.parse(row[i - 1])[0].tag.POS in {'PRTF', "ADJF"}:
                        if row[i] in d1.keys():
                            d1[row[i]].append(row[i-1])
                        else:
                            d1[row[i]] = [row[i-1]]
                if i + 1 < len(row):
                    if morph.parse(row[i + 1])[0].tag.POS in {'NOUN', 'PRTF'}:
                        if row[i] in d1.keys():
                            d1[row[i]].append(row[i + 1])
                        else:
                            d1[row[i]] = [row[i + 1]]
    for i in d1.keys():
        s = list(set(d1[i]))
        s1 = d1[i].copy()
        s1 = filter_city_adj(s1)
        s.sort(key=lambda x: s1.count(x))
        print(i, s)
        writer.writerow([i, s])
"""
получение базы данных для прилагательных, которые чаще всего встречаются с каждым из существительных
"""


import shutil
from distutils.dir_util import copy_tree

import pytest

def pytest_addoption(parser):
    parser.addoption(
        "--network-tests",
        action="store_true",
        default=False,
        help="Run tests that involve network operations. This increases test time.",
    )

def pytest_collection_modifyitems(config, items):
    run_network = config.getoption("--network-tests")
    skip_network = pytest.mark.skip(reason="need --network-tests option to run")
    for item in items:
        # All tests marked with `pytest.mark.network` get skipped unless
        # `--network-tests` passed
        if not run_network and ("network" in item.keywords):
            item.add_marker(skip_network)

@pytest.fixture(scope="session")
def save_path(tmpdir_factory):
    dir = tmpdir_factory.mktemp("temp_data", numbered=False)
    path = str(dir)
    copy_tree("tests/data", path)
    yield path + "/"
    shutil.rmtree(str(tmpdir_factory.getbasetemp()))