有没有一种方法可以在 python 中搜索特定的单词,例如“或”。 我这样做了:
word = raw_input("what do you want to search? ")
for filee in open('text.txt'):
if word in filee:
print "found"
但它会查找字符串“or”。例如;如果 text.txt 中存在单词“world”或包含“or”字符串的其他单词,则打印“found”
有没有办法只搜索那个特定的词“或”?
请您参考如下方法:
使用带有单词边界的regex:
>>> import re
>>> r = re.compile(r'\bor\b')
>>> r.search('and or not')
<_sre.SRE_Match object at 0x7f2f7f8b2ed0>
>>> r.search('and xor not')
