我正在尝试一种方法,可以检查给定短语是否与短语列表中的至少一项匹配并返回它们.输入是短语,短语列表和同义词列表的字典.关键是要使其通用.
这是示例:
phrase = 'This is a little house'
dictSyns = {'little':['small','tiny','little'],
'house':['cottage','house']}
listPhrases = ['This is a tiny house','This is a small cottage','This is a small building','I need advice']
if any('This'+' '+'is'+' '+'a'+x+' '+y == phrase for x in dictSyns['little'] for y in dictSyns['house']):
print 'match'
第一点是我必须创建通用的函数(取决于结果).第二个是我希望此函数返回匹配短语的列表.
在这种情况下,您能否给我一个建议,使方法返回[‘这是一间小房子’,’这是一间小别墅’]?
输出如下:
>>> getMatches(phrase, dictSyns, listPhrases)
['This is a tiny house','This is a small cottage']
解决方法:
我将按以下方式进行处理:
import itertools
def new_phrases(phrase, syns):
"""Generate new phrases from a base phrase and synonyms."""
words = [syns.get(word, [word]) for word in phrase.split(' ')]
for t in itertools.product(*words):
yield ' '.join(t)
def get_matches(phrase, syns, phrases):
"""Generate acceptable new phrases based on a whitelist."""
phrases = set(phrases)
for new_phrase in new_phrases(phrase, syns):
if new_phrase in phrases:
yield new_phrase
代码的根本是单词的分配,形式为new_phrases,它将短语和syns转换为更可用的形式,其中每个元素都是该单词可接受选择的列表:
>>> [syns.get(word, [word]) for word in phrase.split(' ')]
[['This'], ['is'], ['a'], ['small', 'tiny', 'little'], ['cottage', 'house']]
请注意以下几点:
>使用生成器更有效地处理大量组合(而不是一次构建整个列表);
>使用一组进行有效的(成员为O(1),列表为O(n))成员资格测试;
>使用itertools.product
来基于syns生成短语的可能组合(您也可以在实现中使用itertools.ifilter
);和
>符合Style guide.
正在使用:
>>> list(get_matches(phrase, syns, phrases))
['This is a small cottage', 'This is a tiny house']
要考虑的事情:
>字符是什么情况(例如,如何处理“下议院”)?
>标点符号呢?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。