Python 查找关键字,不包括关键字字符串仅作为较大单词的一部分显示的位置
我清理了课文,但真的不明白如何不包括一个较大单词的一部分的单词。例如,如果我查找closed,则不显示enclosedPython 查找关键字,不包括关键字字符串仅作为较大单词的一部分显示的位置,python,keyword,Python,Keyword,我清理了课文,但真的不明白如何不包括一个较大单词的一部分的单词。例如,如果我查找closed,则不显示enclosed def word_search(doc_list, keyword): indices=[] for i,j in enumerate(doc_list): text = j.split() for t in text: clean = t.rstrip('.,!\'\\').lower()
def word_search(doc_list, keyword):
indices=[]
for i,j in enumerate(doc_list):
text = j.split()
for t in text:
clean = t.rstrip('.,!\'\\').lower()
if keyword.lower() in clean:
indices.append(i)
return indices
您可能需要严格的相等性,
关键字.lower()==clean
,而不是包含(关键字.lower()在clean
中)。我更改了此部分
for t in text:
clean = t.rstrip('.,!\'\\').lower()
对此
clean = [t.rstrip('.,!\'\\').lower() for t in text]
它起作用了,但我不明白为什么。我想这就是你想要的。如果没有,请告诉我
x = ['nn', 'anna', 'ara', 'cec', 'aceca', 'racecar', 'mom']
x.sort(key = len, reverse = True)
output = []
for ele in x:
for ele2 in x[x.index(ele):]:
if all(item in ele for item in ele2):
x.remove(ele2)
if ele not in output:
output.append(ele)
print(output)
输出
[“赛车”、“妈妈”]
我认为此代码可以改进。如果是,请建议进行必要的编辑。显示问题所在和预期结果