这是我的第一个问题,我已经完成了研究,但找不到类似的东西。
我的脚本完成后的主要目标: 我希望它根据正则表达式扫描文本文件中的所有行。如果存在匹配,则应将当前行和增量索引添加到字典中。在 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/