Python:在字符串中查找单词

时间:2019-07-10 07:52:15

标签: 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 "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

5 个答案:

答案 0 :(得分:1)

尝试一下:

>>> 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)

答案 1 :(得分:0)

使用一个遍历列表的for循环。然后将变量名更改为更有意义的名称。

kkk="I do not like that car."
wordlist =["like","dislike","hate","cool"]
for word in wordlist:
    if word in kkk:
         print(word)

答案 2 :(得分:0)

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)

答案 3 :(得分:0)

执行此操作的另一种方法是使用集合:

kkk="I do not like that car."
kkk_split = kkk.split(' ')
print({'like', 'dislike', 'hate', 'cool'}.intersection(kkk_split))

答案 4 :(得分:0)

对于您而言,in关键字导致结果冲突。例如,下面的代码段:

sentence = "I do dislike that car."
opinion = ["like","dislike","hate","cool"]
for word in opinion:
    if word in sentence:
        print(word)

同时打印likedislike。相反,您可以使用正则表达式零宽度字边界\b以获得准确的结果,如下所示:

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)

仅打印dislike