Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

python - Find matching words in a list and a string

I am writing some code in Python and I want to check if a list of words is in a long string. I know I could iterate through it multiple times and that may be the same thing but I wanted tp see if there is a faster way to do it. What I am currently doing is this:

    all_text = 'some rather long string'
    if "motorcycle" in all_text or 'bike' in all_text or 'cycle' in all_text or 'dirtbike' in all_text:
        print 'found one of em'

but what I want to do is this:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
if item in keyword_list in all_text:
            print 'found one of em'

Is there anyway to do this efficiently? I realize I could do:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
for item in keyword_list:
      if item in all_text:
            print 'found one of em'

But it seems like there would be a better way once the keyword list becomes long.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You still have to check them all at least until one is found to be in the text, but it can be more concise:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']

if any(word in all_text for word in keyword_list):
    print 'found one of em'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...