简体   繁体   中英

Python: find the word in string

I want to find the word in string like this below:

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

But since my code is very long, I would like to keep it shorter:

if "like" in kkk or "dislike" in kkk or "hate" in kkk or "cool" in kkk:
    #print "like" 
    #unable to do it this way

Then I tried to use another way, but it didn't work:

a=["like","dislike","hate","cool"]

if any(x in kkk for x in a):
    print(x)
    #NameError: name 'x' is not defined

Try this :

>>> kkk="I do not like that car."
>>> a=["like","dislike","hate","cool"]
>>> print(*[x for x in a if x in kkk])
like

This list comprehension is same as the following :

for x in a:
    if x in kkk:
        print(x)

Use a for loop that iterates over the list. And change your variable names to something more meaningful.

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

any won't return the found word; the best alternative is perhaps 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')

If you don't want to handle an exception and instead get None :

word = next((k for k in keywords if k in sentence), None)

another way of doing this is using sets:

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

For your case, in keyword cause conflicting result. For example, the snippet below:

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

prints both like and dislike . Instead, you can use regular expression zero-width word boundary \\b for accurate result as:

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)

which prints dislike only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM