python - 为什么我的 for 循环只在第一项上执行?
问题描述
我有一个要与文件匹配的正则表达式列表,以及匹配发生的行号以添加到特定于该正则表达式的列表中。
regexes = [r"Repl ex\s+0\s+x\s+1", r"Repl ex.*1\s+x\s+2", r"Repl ex.*2\s+x\s+3",
r"Repl ex.*3\s+x\s+4", r"Repl ex.*4\s+x\s+5", r"Repl ex.*5\s+x\s+6",
r"Repl ex.*6\s+x\s+7", r"Repl ex.*7\s+x\s+8", r"Repl ex.*8\s+x\s+9",
r"Repl ex.*9\s+x\s+10", r"Repl ex.*10\s+x\s+11", r"Repl ex.*11\s+x\s+12",
r"Repl ex.*12\s+x\s+13", r"Repl ex.*13\s+x\s+14", r"Repl ex.*14\s+x\s+15",
r"Repl ex.*15\s+x\s+16", r"Repl ex.*16\s+x\s+17", r"Repl ex.*17\s+x\s+18",
r"Repl ex.*18\s+x\s+19"]
exchanges = [[] for i in range(19)]
# open the md.log file
f = open('myfile', 'r')
for x in range(19):
for i, line in enumerate(f):
if re.compile(regexes[x]).match(line):
exchanges[x].append(i)
上面的代码给出了 exchange[0] 的预期结果,但之后返回以下 17 个项目的空列表。如果我用“1”代替“x”运行它,我会得到下一个正则表达式的正确结果,所以我知道正则表达式是匹配的。
解决方案
您正在尝试使用相同的文件描述符一遍又一遍地迭代同一个文件。每当您读取一行时,描述符都会指向文件中的下一个。在第一次迭代中,文件将被完全读取,并且描述符将不再有要读取的行,这就是为什么您的内部循环不会多次执行的原因。要解决此问题,请将文件内容存储在列表中并对其进行迭代。
exchanges = [[] for i in range(19)]
# open the md.log file
f = open('myfile', 'r')
contents = f.readlines()
f.close()
for x in range(19):
for i, line in enumerate(contents):
if re.compile(regexes[x]).match(line):
exchanges[x].append(i)
推荐阅读
- java - Elasticsearch 中 49 条记录后出现异常
- angularjs - 如何将 AngularJS 代码写入 Angular 9?
- spring - Spring Boot Rest 模板保持连接活跃
- unix - 如何在 shell 脚本中使用不同类型的分隔符提取文件名的子字符串?
- c++ - 在向量 C++ 中排列奇数和偶数
- java - Java SSL - 添加到 CACERTS 的证书在重新启动后不起作用
- c# - 如何编写代码为paytm发起交易api生成校验和
- vba - 访问表单的希伯来语日期选择器
- javascript - 从内容脚本向弹出脚本发送消息
- yocto - 如何在 yocto 中使用外部工具链