gpt4 book ai didi

python - 返回给定短语的匹配列表

转载 作者:行者123 更新时间:2023-12-01 04:57:10 25 4
gpt4 key购买 nike

我正在尝试创建一种方法,可以检查给定短语是否与短语列表中的至少一项匹配并返回它们。输入是短语、短语列表和同义词列表词典。重点是要使其具有普遍性。

示例如下:

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']

我可以创建一个代码,可以在这个返回 bool 的示例中执行此操作:

if any('This'+' '+'is'+' '+'a'+x+' '+y == phrase for x in dictSyns['little'] for y in dictSyns['house']):
print 'match'

第一点是我必须创建通用的函数(取决于结果)。第二个是我希望这个函数返回匹配短语的列表。

您能否给我一个建议,让我在这种情况下如何执行此操作,以便该方法返回 ['This is a tiny house','This is a Smallott']

输出如下:

>>> 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

代码的根源是 words 的赋值,在 new_phrases ,这会转换 phrasesyns转换为更可用的形式,一个列表,其中每个元素都是该单词的可接受选项的列表:

>>> [syns.get(word, [word]) for word in phrase.split(' ')]
[['This'], ['is'], ['a'], ['small', 'tiny', 'little'], ['cottage', 'house']]

注意以下几点:

  • 使用生成器更有效地处理大量组合(而不是立即构建整个列表);
  • 使用set用于高效( O(1) ,与 O(n) 用于列表)成员资格测试;
  • 使用 itertools.product 生成 phrase 的可能组合基于syns (您也可以使用 itertools.ifilter 来实现);和
  • Style guide合规性。

使用中:

>>> list(get_matches(phrase, syns, phrases))
['This is a small cottage', 'This is a tiny house']

需要考虑的事情:

  • 字符大小写如何(例如 "House of Commons" 应如何处理)?
  • 标点符号怎么样?

关于python - 返回给定短语的匹配列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27123954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com