Beispiel #1
0
def assert_first_inflected_variant(word, grammemes, result, morph):
    inflected_variants = [p.inflect(set(grammemes)) for p in morph.parse(word)]
    inflected_variants = [v for v in inflected_variants if v]
    # inflected_variants = morph.inflect(word, grammemes)
    assert len(inflected_variants)

    inflected = inflected_variants[0]
    assert restore_capitalization(inflected.word, word) == result
Beispiel #2
0
def assert_first_inflected_variant(word, grammemes, result):
    inflected_variants = [p.inflect(set(grammemes)) for p in morph.parse(word)]
    inflected_variants = [v for v in inflected_variants if v]
    # inflected_variants = morph.inflect(word, grammemes)
    assert len(inflected_variants)

    inflected = inflected_variants[0]
    assert restore_capitalization(inflected.word, word) == result
Beispiel #3
0
def sform(num, word):
    if word.lower() in broken:
        formed = form(num, broken[word.lower()])
    else:
        parsed = morph.parse(word)[0]
        formed = parsed.make_agree_with_number(num).word
    restored = restore_capitalization(formed, word)
    return restored
def inflect(morph, text, required_grammemes):
    inflected = []
    for token in text.split():
        inflected_Parse_obj = morph.parse(token)[0].inflect(
            set(required_grammemes))
        inflected.append(
            restore_capitalization(inflected_Parse_obj.word, token
                                   ) if inflected_Parse_obj else token)
    return " ".join(inflected)
Beispiel #5
0
 def prepositional(text):
     morph = pymorphy2.MorphAnalyzer()
     tokens = text.split()
     inflected = [
         restore_capitalization(
             morph.parse(tok)[0].inflect({'loct'}).word,
             tok
         )
         for tok in tokens
     ]
     return ' '.join(inflected)
Beispiel #6
0
def pluralize_word(word, number):
    """
    Pluralize a word according to a given number.
    """
    assert isinstance(number, six.integer_types)

    parsed = morph.parse(word)
    if isinstance(parsed, list):
        pluralized = parsed[0].make_agree_with_number(number)
        if pluralized is not None:
            return restore_capitalization(pluralized.word, word)

    return word
Beispiel #7
0
def pluralize_word(word, number):
    """
    Согласует слово с числом
    """
    assert isinstance(number, six.integer_types)

    parsed = morph.parse(word)
    if isinstance(parsed, list):
        pluralized = parsed[0].make_agree_with_number(number)
        if pluralized is not None:
            return restore_capitalization(pluralized.word, word)

    return word
Beispiel #8
0
def inflect_word_from_nomn(word, forms, *args, **kwargs):
    parsed = morph.parse(word)

    forms_cache = []
    for p in parsed:
        if p.tag.POS not in DONT_INFLECT_FORMS:
            if (forms in p.tag
                    and (p.normal_form == p.word or 'NOUN' not in p.tag)):
                return restore_capitalization(p.word, word)

            if 'nomn' not in p.tag:
                continue

            forms_cache.append(p)

    if len(forms_cache) > 0:
        p = forms_cache[0]
        parsed_word = p.inflect(forms)

        if parsed_word is not None:
            return restore_capitalization(parsed_word.word, word)

    return word
Beispiel #9
0
def inflect_word_from_nomn(word, forms, *args, **kwargs):
    parsed = morph.parse(word)

    forms_cache = []
    for p in parsed:
        if p.tag.POS not in DONT_INFLECT_FORMS:
            # Нам необходима определенная словоформа. Остальные пропускаем
            if (forms in p.tag and (p.normal_form == p.word or 'NOUN' not in p.tag)):
                return restore_capitalization(p.word, word)

            if 'nomn' not in p.tag:
                continue

            forms_cache.append(p)

    if len(forms_cache) > 0:
        p = forms_cache[0]
        parsed_word = p.inflect(forms)

        if parsed_word is not None:
            return restore_capitalization(parsed_word.word, word)

    return word
    def right_text_spelling_with_number(self, number, text):
        agreed = []
        for token in text.split():
            parse_result = self.morph.parse(token)
            for option in parse_result:
                if option.normal_form == token:
                    word = option
                    break
            else:
                word = parse_result[0]

            agreed_Parse_obj = word.make_agree_with_number(number)
            agreed.append(
                restore_capitalization(agreed_Parse_obj.word, token
                                       ) if agreed_Parse_obj else token)
        return " ".join(agreed)
Beispiel #11
0
 def inflect_all(self, text, required_grammemes):
     '''
         функция, склоняющая целые фразы, сохраняя большие буквы
     '''
     words = text.split()
     inflected = []
     for word in words:
         try:
             parsed_word = self.parse(word)[0]  # Разберем слово
             if 'nomn' in str(parsed_word.tag):  # Если именительный падеж, то переводим в мн.ч
                 inflected.append(restore_capitalization(
                     parsed_word.inflect(required_grammemes).word,
                     word))
             else:   # Если не именительный падеж то не меняем слово
                 inflected.append(word)
         except:
             inflected.append(word)
     return " ".join(inflected)
Beispiel #12
0
def inflect_word(word, forms, specifying_forms=None):
    """
    Converts a word into a given form.
    """
    parsed = morph.parse(word)

    for p in parsed:
        if p.tag.POS in DONT_INFLECT_FORMS:
            return word
        else:
            if isinstance(specifying_forms,
                          set) and specifying_forms not in p.tag:
                continue

            parsed_word = p.inflect(forms)
            if parsed_word is not None:
                return restore_capitalization(parsed_word.word, word)

    return word
Beispiel #13
0
def inflect_word(word, forms, specifying_forms=None):
    """
    Склоняет одно слово в переданную форму
    """
    parsed = morph.parse(word)

    for p in parsed:
        if p.tag.POS in DONT_INFLECT_FORMS:
            return word
        else:
            # Нам необходима определенная словоформа. Остальные пропускаем

            if isinstance(specifying_forms, set) and specifying_forms not in p.tag:
                continue

            parsed_word = p.inflect(forms)
            if parsed_word is not None:
                return restore_capitalization(parsed_word.word, word)

    return word
Beispiel #14
0
def inflect_word(word, forms, specifying_forms=None):
    """
    Склоняет одно слово в переданную форму
    """
    parsed = morph.parse(word)

    for p in parsed:
        if p.tag.POS in DONT_INFLECT_FORMS:
            return word
        else:
            # Нам необходима определенная словоформа. Остальные пропускаем

            if isinstance(specifying_forms, set) and specifying_forms not in p.tag:
                continue

            parsed_word = p.inflect(forms)
            if parsed_word is not None:
                return restore_capitalization(parsed_word.word, word)

    return word
Beispiel #15
0
    def get_context_data(self, **kwargs):
        c = super().get_context_data(**kwargs)
        c["phone"] = '+7 (977) 801-25-41'
        c["email"] = '*****@*****.**'
        c["price"] = 1000
        c["price45"] = 800
        c["menu_id"] = "services"

        h = self.request.META.get('HTTP_HOST', '')  # hostname
        c['city_host'] = h.split('.')[0] if len(h.split('.')) >= 3 else h
        c['remote_only'] = h != settings.DOMAIN and \
            c['city_host'] != 'moskva'

        city = cities.get(c['city_host'], None)
        c['city_specific'] = city is not None
        city = cities.get(c['city_host'], 'Россия')

        c['city'] = city
        c['in_city'] = restore_capitalization(
            morph.parse(city)[0].inflect({'loct'}).word, city)
        c['cities'] = ({
            'name': 'Москва',
            'url': 'moskva.{}'.format(settings.DOMAIN),
        }, {
            'name': 'Санкт-Петербург',
            'url': 'spb.{}'.format(settings.DOMAIN),
        })

        c['menu'] = Menu([
            (
                'index',
                {
                    'title': 'Главная',
                    # 'img': staticfiles_storage.url('favicon.png'),
                    'url': reverse('index'),
                }),
            ('articles', {
                'title': 'Статьи',
                'url': reverse('articles:index'),
            } if c['user'].is_superuser else None),
            ('faq', {
                'title': 'Вопросы',
                'url': reverse('faq'),
            }),
            ('pay', {
                'title': 'Оплата',
                'url': reverse('pay'),
            }),
            # ('agreement', {
            #     'title': 'Правила',
            #     'url': reverse('agreement'),
            # }),
            ('contacts', {
                'title': 'Контакты',
                'url': reverse('contacts'),
            }),
            ('students', {
                'title': 'Ученики',
                'url': reverse('students'),
            } if c['user'].is_superuser else None),
        ])
        return c