python - For 循环应该向字典添加条目但只保留一个

标签 python loops dictionary data-structures

这是我的第一个问题,我已经完成了研究,但找不到类似的东西。

我的脚本完成后的主要目标: 我希望它根据正则表达式扫描文本文件中的所有行。如果存在匹配,则应将当前行和增量索引添加到字典中。在 EOF 处,现在填充的字典应写入新文件中。

当前问题: 当运行 for 循环来扫描行时,尽管扫描仪实际上找到了多个匹配项,但字典似乎从未获得超过一个条目(当匹配为 true 时,通过简单的打印语句进行确认。我错过了什么?

for inputfile in inputfiles:
print("Processing "+ inputfile)

inputfile = os.path.join(filespath,inputfile)

with open (inputfile, "r", encoding="UTF-8") as infile:
    alllines = infile.readlines()

matched_lines = {}
int_index = 1
indexer = str(int_index).zfill(5)
for line in alllines:
    if re.search(match_string,line,flags=0):
        matched_lines[indexer] = line
        int_index += 1
print (matched_lines.items())

这是它的输出: 处理测试文件1.txt dict_items([('00001', 'Zeile 5\n')])

但是这个“Zeile 5\n”(正则表达式匹配为 5$)在它正在扫描的文本文件中多次出现。该文件看起来像这样:

Zeile 3
Zeile 4
Zeile 5

Zeile 1
Zeile 2
Zeile 3
Zeile 4
Zeile 5

Zeile 1
Zeile 2
Zeile 3
Zeile 4
Zeile 5

Zeile 1
Zeile 2
Zeile 3
Zeile 4
Zeile 5

Zeile 1
Zeile 2
Zeile 3

等等

有什么想法吗?

最佳答案

第一次迭代后您永远不会更新索引器,请看:

int_index = 1
indexer = str(int_index).zfill(5)

for line in alllines:
    if re.search(match_string,line,flags=0):
        matched_lines[indexer] = line # indexer was always the same!
        int_index += 1
        indexer = str(int_index).zfill(5) # this should fix it

关于python - For 循环应该向字典添加条目但只保留一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54517654/

相关文章:

python - Tkinter - 如何将实例变量传递给另一个类?

python - 使用 Pandas 将数据框中的 Python 对象列转换为没有日期的时间

c# - 尝试 C# 将 Json 解析为带有内部数组的字典

python - 当键在字典中时发生KeyError

python - QProgressBar不显示复制进度

for 循环中的 C++ 引用

python - 如何使用循环 Pandas 将值添加到列

java Codingbat notAlone — 为什么它不适用于这个特定示例

ios - iOS 版 MapBox,自定义样式

python - 在 AWS Lambda 上使用来自 Python 的 NodeJS 4 脚本