Python-遍历字符串列表并分组部分匹配的字符串
作者:互联网
所以我有一个字符串列表如下:
list = ["I love cat", "I love dog", "I love fish", "I hate banana", "I hate apple", "I hate orange"]
我如何遍历列表并在没有给定关键字的情况下将部分匹配的字符串分组.结果应如下所示:
list 1 = [["I love cat","I love dog","I love fish"],["I hate banana","I hate apple","I hate orange"]]
非常感谢.
解决方法:
尝试建立一个反向索引,然后您可以选择任何喜欢的关键字.这种方法忽略了单词顺序:
index = {}
for sentence in sentence_list:
for word in set(sentence.split()):
index.setdefault(word, set()).add(sentence)
或采用这种方法,它通过所有可能的全字词前缀来索引索引:
index = {}
for sentence in sentence_list:
number_of_words = length(sentence.split())
for i in xrange(1, number_of_words):
key_phrase = sentence.rsplit(maxsplit=i)[0]
index.setdefault(key_phrase, set()).add(sentence)
然后,如果您想查找所有包含关键字的句子(或者,从短语开始,如果那是您的索引):
match_sentences = index[key_term]
或一组给定的关键字:
matching_sentences = reduce(list_of_keywords[1:], lambda x, y: x & index[y], initializer = index[list_of_keywords[0]])
现在,您可以通过使用这些索引生成列表理解来生成句子,从而生成几乎由术语或短语的任何组合组成的列表.例如,如果您构建了词组前缀索引,并希望将所有内容都按前两个词组进行分组:
return [list(index[k]) for k in index if len(k.split()) == 2]
标签:string-matching,grouping,fuzzy-search,python 来源: https://codeday.me/bug/20191026/1937668.html