Python 2个字符串按顺序返回不同的常用词
以下是两个字符串:Python 2个字符串按顺序返回不同的常用词,python,python-3.x,Python,Python 3.x,以下是两个字符串: firstText = 'I LoVe LOVE You' secondText = 'Love is a cool feeling love you too' 回报应该是['LoVe','You'] 但我只能得到[‘爱’、‘爱’、‘你’] 下面是对代码的简单调整,以获得所需的结果: firstText = 'I LoVe LOVE You' secondText = 'Love is a cool feeling love you too' words_list =
firstText = 'I LoVe LOVE You'
secondText = 'Love is a cool feeling love you too'
回报应该是['LoVe','You']
但我只能得到[‘爱’、‘爱’、‘你’]
下面是对代码的简单调整,以获得所需的结果:
firstText = 'I LoVe LOVE You'
secondText = 'Love is a cool feeling love you too'
words_list = []
i = 0
for word in firstText.upper().split():
if word in secondText.upper().split():
if word not in " ".join(words_list).upper():
words_list.append(firstText.split()[i])
i += 1
print(words_list)
问题是您正在比较不同大小写格式的字符串,例如LoVe和LoVe,所以比较不匹配。在这里,我用大写字母表示比较前保存的所有单词。通过这样做,我比较了可以一起比较的东西
如果您想了解其他信息,请告诉我。请思考您在此处添加到列表中的内容,以及在不添加列表中的单词时要比较的内容。此外,请不要将名称列表用于变量。它隐藏了内置的类型列表。更简单的方法是使用set intersection
firstText = 'I LoVe LOVE You'
secondText = 'Love is a cool feeling love you too'
words_list = []
i = 0
for word in firstText.upper().split():
if word in secondText.upper().split():
if word not in " ".join(words_list).upper():
words_list.append(firstText.split()[i])
i += 1
print(words_list)