Python:在字符串中查找单词
我想在下面这样的字符串中查找单词:Python:在字符串中查找单词,python,Python,我想在下面这样的字符串中查找单词: kkk="I do not like that car." if "like" in kkk: print("like") elif "dislike" in kkk: print("dislike") elif "hate" in kkk: print("hate") elif "cool" in kkk: print("cool") 但由于我的代码很长,我希望将其缩短: if "like" in kkk or "disl
kkk="I do not like that car."
if "like" in kkk:
print("like")
elif "dislike" in kkk:
print("dislike")
elif "hate" in kkk:
print("hate")
elif "cool" in kkk:
print("cool")
但由于我的代码很长,我希望将其缩短:
if "like" in kkk or "dislike" in kkk or "hate" in kkk or "cool" in kkk:
#print "like"
#unable to do it this way
然后我试着用另一种方法,但没有成功:
a=["like","dislike","hate","cool"]
if any(x in kkk for x in a):
print(x)
#NameError: name 'x' is not defined
使用遍历列表的for循环。并将变量名更改为更有意义的名称
kkk="I do not like that car."
wordlist =["like","dislike","hate","cool"]
for word in wordlist:
if word in kkk:
print(word)
试试这个:
>>> kkk="I do not like that car."
>>> a=["like","dislike","hate","cool"]
>>> print(*[x for x in a if x in kkk])
like
此列表理解与以下内容相同:
for x in a:
if x in kkk:
print(x)
any
不会返回找到的单词;最好的选择可能是next
:
keywords = ["like", "dislike", "hate", "cool"]
sentence = "I do not like that car."
try:
word = next(k for k in keywords if k in sentence)
print(word)
except StopIteration:
print('Not found')
如果您不想处理异常而改为获取None
:
word = next((k for k in keywords if k in sentence), None)
另一种方法是使用集合:
kkk="I do not like that car."
kkk_split = kkk.split(' ')
print({'like', 'dislike', 'hate', 'cool'}.intersection(kkk_split))
对于您的情况,关键字中的
会导致冲突结果。例如,下面的代码段:
sentence = "I do dislike that car."
opinion = ["like","dislike","hate","cool"]
for word in opinion:
if word in sentence:
print(word)
打印喜欢的
和不喜欢的
。相反,您可以使用正则表达式零宽度字边界来获得准确的结果,如下所示:
import re
sentence = "I do dislike that car."
opinion = ["like","dislike","hate","cool"]
for word in opinion:
if re.search(r'\b'+word+r'\b', sentence):
print(word)
只打印不喜欢
。变量名的选择有点奇怪和不寻常…为什么不为a中的x使用一个简单的for循环
-->:如果kkk中的x:print(x)
?请注意,拆分
并设置交集不一定会产生与
@deceze中的相同的结果,这是怎么回事?'like'与{'like'}。交集({'He','likes','cars')
。的确,它不适用于子字符串,但我认为作者要求的是完整的单词