对于循环应该条目添加到字典,而是只保留一个

问题描述 投票:1回答:2

这是我的第一个问题在这里,我已经做了研究,但不能真正找到类似的东西。

我的剧本的主要目标,当它这样做:我想它扫描对正则表达式的文本文件中的所有行。如果存在匹配,当前行和增量索引应被添加到dicionary。在EOF现在充满字典应写入新文件。

目前存在的问题:当运行for循环扫描从来没有字典似乎得到多个条目线,尽管真正找到多个匹配扫描(通过简单的print语句时确认比赛是真实的我错过了什么?

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

这是它输出:处理TESTFILE的1.txt dict_items([( '00001', '5 Zeile \ 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

等等

有任何想法吗?

python loops dictionary data-structures
2个回答
2
投票

你永远更新索引的第一个循环之后,请看:

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

1
投票

在你的循环更新int_index但不indexer。所以每次循环使用相同的indexer值,并覆盖在dict相同的入口,所以你只能有一个被保存的一个值。

© www.soinside.com 2019 - 2024. All rights reserved.