【发布时间】:2021-07-12 19:05:50
【问题描述】:
我正在编写一个 Python 脚本,该脚本将遍历包含一堆文件的目录并提取与特定模式匹配的字符串。 更具体地说,我正在尝试提取序列号和最大限制的值,这些行看起来像这样:
#serial number = 642E0523D775
max-limit=50M/50M
我有脚本来遍历文件,但我在实际打印我想要的值时遇到了问题。我没有打印值,而是得到“Nothing fount”输出。
我认为这可能与我正在使用的正则表达式有关,但我一生都无法弄清楚如何制定它。
到目前为止我想出的脚本:
import os
import re
#Where I'm searching
user_input = "/path/to/files/"
directory = os.listdir(user_input)
#What I'm looking for
searchstring = ['serial number', 'max-limit']
re_first = re.compile ('serial.\w.*')
re_second = re.compile ('max-limit=\w*.\w*')
#Regex combine
regex_list = [re_first, re_second]
#Looking
for fname in directory:
if os.path.isfile(user_input + os.sep + fname):
# Full path
f = open(user_input + os.sep + fname, 'r')
f_contents = f.read()
content = fname + f_contents
files = os.listdir(user_input)
lines_seen = set()
for f in files:
print(f)
if f not in lines_seen: # not a duplicate
for regex in regex_list:
matches = re.findall(regex, content)
if matches != None:
for match in matches:
print(match)
else:
print('Nema')
f.close()
【问题讨论】:
-
您不应在正则表达式中包含前导/尾随
/分隔符。regex=r'^[\w&.-]+$' -
感谢您的建议!我不得不进一步更改正则表达式以匹配我必须分析的文件的特异性,我已经用最终脚本更新了原始问题。
标签: python python-3.x regex