how can i search for a specific word in python?

2020-04-24 11:10发布

Is there a way to search a specific word in python, like 'or'. I did this:

word = raw_input("what do you want to search? ")
for filee in open('text.txt'):
   if word in filee:
     print "found"

But it looks for the string 'or'. For example; if the word 'world' exists in text.txt or some other word containing the 'or' string it prints "found"

Is there a way to search only for that specific word 'or' ?

1条回答
Root(大扎)
2楼-- · 2020-04-24 11:34

Use regex with word boundaries:

>>> import re
>>> r = re.compile(r'\bor\b')
>>> r.search('and or not')
<_sre.SRE_Match object at 0x7f2f7f8b2ed0>
>>> r.search('and xor not')
查看更多
登录 后发表回答