gpt4 book ai didi

python - 我如何在 python 中搜索特定的单词?

转载 作者:太空宇宙 更新时间:2023-11-04 07:01:42 25 4
gpt4 key购买 nike

有没有一种方法可以在 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')

关于python - 我如何在 python 中搜索特定的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20427267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com