嘗試建立一個倒排索引,然後你就可以挑你最喜歡的關鍵字。這種方法忽略了詞序:
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]
你有什麼已經嘗試過?一些入門代碼讓其他人知道你已經嘗試了什麼,以及你陷入困境的地方有助於構建答案。 – TheF1rstPancake
['itertools groupby'](https://docs.python.org/2/library/itertools.html#itertools.groupby)將對此有所幫助。 – RoadRunner
你如何定義部分匹配? – wwii