![](/img/trans.png)
[英]Include surrounding lines of text file match in output using Python 2.7.3
[英]Using regex in Python 2.7.3 to search text and output matches
我正在努力完成标题所说的内容。 该程序用于从指定路径读取.txt文件并匹配代码中指定的术语。 这是我到目前为止:
import re
source = open("C:\\test.txt", "r")
lines = []
for line in source:
line = line.strip()
lines.append(line)
if re.search('reply', line):
print 'found: ', line
正如您所看到的,我使用re.search指定术语“回复”,但这限制了我一个术语。 我知道有一种方法可以指定要搜索的单词列表或字典,但我的尝试失败了。 我认为有可能创建一个类似于...的列表
keywords = ['reply', 'error', 'what']
...但是尽管我在这个网站上已经阅读过,但我似乎无法将其正确地纳入代码中。 任何建议或协助非常感谢!
PS。 如果我想让搜索区域敏感,我是否可以使用...
"(.*)(R|r)eply(.*)"
...在我想要找到的术语列表中?
单程:
import re
source = open("input", "r")
lines = []
keywords = ['reply', 'error', 'what']
# join list with OR, '|', operators
# re.I makes it case-insensitive
exp = re.compile("|".join(keywords), re.I)
for line in source:
line = line.strip()
lines.append(line)
if re.search(exp, line):
print 'found: ', line
使用re.search(),您传递一个字符串,但您可以指定非常复杂的模式。 请参阅Python re模块上的文档,其中有关于“正则表达式语法”的部分。
事实上你的问题答案是...... "R|r"
搜索“R”或“r”,所以"reply|error|what"
搜索“回复”,“错误”或“什么”。
PS。 如果我想让搜索区域敏感,我是否可以使用......“
(.*)(R|r)eply(.*)
”
不需要.*
位(它可能会使你的代码变慢)。 re.search()函数在字符串中的任何位置查找匹配项。 (R|r)eply
将寻找'reply'或'Reply',它将不匹配'REPLY'或'rePly'。
如果你想要一个不区分大小写的搜索,你可以传递给re.search()
的flags=re.IGNORECASE
选项。 例如:
re.search('reply', line, flags=re.IGNORECASE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.