[英]Why is this giving me “list index out of range”? I'm trying to find names in a list and names can be two words long or more
[英]What can I use for finding names words in two list? Python
我有興趣在兩個列表中找到相同的單詞。 我在 text_list 中有兩個單詞列表,我也詞干了這些單詞。
text_list = [['i', 'am', 'interest' ,'for', 'this', 'subject'], ['this', 'is', 'a', 'second', 'sentence']]
words_list = ['a', 'word', 'sentence', 'interesting']
所以我需要這個 output:
same_words= ['a', 'sentence', 'interest']
您需要對兩個列表都應用詞干提取,例如interesting
和interest
之間存在差異,如果您僅對words_list
應用詞干提取,則Sentence
變為sentenc
,因此,將詞干分析器應用於兩個列表,然后找到共同元素:
from nltk.stem import PorterStemmer
text_list = [['i', 'am', 'interest','for', 'this', 'subject'], ['this', 'is', 'a', 'second', 'sentence']]
words_list = ['a', 'word', 'sentence', 'interesting']
ps = PorterStemmer()
words_list = [ps.stem(w) for w in words_list]
text_list = [list(map(ps.stem,i)) for i in text_list]
answer = []
for i in text_list:
answer.append(list(set(words_list).intersection(set(i))))
output = sum(answer, [])
print(output)
>>> ['interest', 'a', 'sentenc']
有一個名為fuzzywuzzy
的package,它允許您將列表中的字符串與另一個列表中的字符串進行近似匹配。
首先,您需要將嵌套列表展平為具有唯一字符串的列表/集。
from itertools import chain
newset = set(chain(*text_list))
{'sentence', 'i', 'interest', 'am', 'is', 'for', 'a', 'second', 'subject', 'this'}
接下來,從fuzzywuzzy
package,我們導入fuzz
function。
from fuzzywuzzy import fuzz
result = [max([(fuzz.token_set_ratio(i,j),j) for j in newset]) for i in words_list]
[(100, 'a'), (57, 'for'), (100, 'sentence'), (84, 'interest')]
通過查看此處, fuzz.token_set_ratio
實際上可以幫助您將 words_list 中的每個元素與words_list
中的所有元素進行newset
,並給出兩個元素之間匹配字母的百分比。 您可以刪除max
以查看它的完整列表。 ( for
中的一些字母在word
中,這就是為什么它在這個元組列表中也顯示了 57% 的匹配。稍后您可以使用 for 循環和百分比容差來刪除低於百分比容差的匹配)
最后,您將使用map
來獲得您想要的 output。
similarity_score, fuzzy_match = map(list,zip(*result))
fuzzy_match
Out[40]: ['a', 'for', 'sentence', 'interest']
如果您的輸入不是通常的 ASCII 標准,您可以在fuzz.token_set_ratio
中放置另一個參數
a = ['У', 'вас', 'є', 'чашка', 'кави?']
b = ['ви']
[max([(fuzz.token_set_ratio(i, j, force_ascii= False),j) for j in a]) for i in b]
Out[9]: [(67, 'кави?')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.