Найти - Пользователи
Полная версия: Есть две строки или два списка. Надо удалить окончания.
Начало » Центр помощи » Есть две строки или два списка. Надо удалить окончания.
1 2
lioha1984
Есть две строки или два списка.
stem_rules = ('less', ‘ship’, ‘ing’, ‘es’, ‘ly’,'s')
text = ('friends', ‘very’, ‘friendly’, ‘keeping’, ‘friendship’)
Нужно основываясь на stem_rules удалить окончания из text.

получить: ('friend', ‘very’, ‘friend’, ‘keep’, ‘friend’)

Как это сделать при помощи функций map(),filter() и т.д., и функции lambda?
botinag
lioha1984
удалить окончания
что это значит?
Распишите по-нормальному задачу. Желательно с примером что подается на входи и что имеем на выходе.
lioha1984
отредактировал.
botinag
stem_rules = ('less', 'ship', 'ing', 'es', 'ly','s')
text = ('friends', 'very', 'friendly', 'keeping', 'friendship')
def del_end(word, ends = stem_rules):
    for x in ends:
        if word.endswith(x):
            word = word[:-len(x)]
            break  # удаляем только первое попавшееся окончание
    return word

>>> map(del_end, text)
['friend', 'very', 'friend', 'keep', 'friend']
>>> map(lambda x: del_end(x), text) # или map(lambda x: del_end(x, stem_rules), text)
['friend', 'very', 'friend', 'keep', 'friend']
>>> f = lambda x: [del_end(y) for y in x]
>>> f(text)
['friend', 'very', 'friend', 'keep', 'friend']
Получилось довольно исскуственно. Тут наверное стоит смотреть в сторону регулярок, а я в них не разбираюсь.
Ну а спомощью filter можно найти те слова из списка у которых отсутствуют искомые окончания:
>>> filter(lambda x: x == del_end(x), text)
('very',)
py.user.next
Лучше ясно написать.
>>> stem_rules = ('less', 'ship', 'ing', 'es', 'ly','s')
>>> text = ('friends', 'very', 'friendly', 'keeping', 'friendship')
>>> 
>>> def f(lst, ends):
...     for i in lst:
...         o = i
...         for j in ends:
...             if i.endswith(j):
...                o = i[:-len(j)]
...                break
...         yield o
... 
>>> tuple(f(text, stem_rules))
('friend', 'very', 'friend', 'keep', 'friend')
>>>

Beautiful is better than ugly.
Simple is better than complex.
Complex is better than complicated.

Add
Добавил break после заметки от terabayt
Paranoia_Agent
Как вариант:
http://python.su/forum/topic/25775/
terabayt
print(tuple(map(lambda x: x.rstrip([i for i in stem_rules + ('',) if x.endswith(i)][0]), text)))
terabayt
py.user.next
>>> stem_rules = ('less', 'ship', 'ing', 'es', 'ly','s')
>>> text = ('fearless', 'heroes')
>>> 
>>> def f(lst, ends):
...     for i in lst:
...         o = i
...         for j in ends:
...             if i.endswith(j):
...                o = i[:-len(j)]
...         yield o
... 
>>> tuple(f(text, stem_rules))
('fearles', 'heroe')
>>>
py.user.next
terabayt
print(tuple(...

>>> stem_rules = ('ing',)
>>> text = ('singing',)
>>> 
>>> print(tuple(map(lambda x: x.rstrip([i for i in stem_rules + ('',) if x.endswith(i)][0]), text)))
('s',)
>>>
terabayt
py.user.next
да, что-то я провтыкал с strip )
print(tuple(map(lambda x: x[:len(x)-len([i for i in stem_rules + ('',) if x.endswith(i)][0])], text)))
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB