如何在python中搜索特定单词? [英] how can i search for a specific word in python?

查看:109
本文介绍了如何在python中搜索特定单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在python中搜索特定的单词,比如'or'.我是这样做的:

word = raw_input("你想搜索什么?")对于 open('text.txt') 中的文件:如果文件中的单词:打印找到"

但它寻找字符串'or'.例如;如果 text.txt 中存在单词world"或其他包含or"字符串的单词,则它会打印找到"

有没有办法只搜索那个特定的词 'or' ?

解决方案

使用 regex 与单词边界:

<预><代码>>>>进口重新>>>r = re.compile(r'\bor\b')>>>r.search('和与否')<_sre.SRE_Match 对象在 0x7f2f7f8b2ed0>>>>r.search('和异或')

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' ?

解决方案

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

这篇关于如何在python中搜索特定单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆