这是我的第一个问题在这里,我已经做了研究,但不能真正找到类似的东西。
我的剧本的主要目标,当它这样做:我想它扫描对正则表达式的文本文件中的所有行。如果存在匹配,当前行和增量索引应被添加到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
等等
有任何想法吗?
你永远更新索引的第一个循环之后,请看:
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
在你的循环更新int_index
但不indexer
。所以每次循环使用相同的indexer
值,并覆盖在dict
相同的入口,所以你只能有一个被保存的一个值。