【发布时间】:2020-01-31 16:51:02
【问题描述】:
我想从 res 列表中获取那些具有字符串的行(其中至少 4 个,o 一个 O 代替零)以及名称。使用下面的脚本,我得到没有名称的新行,只有行有 0 和 1。
我有一个包含如下名称和数字行的文本文件:
txt 文件中的行:
John Johns 1-1, 1-2
Adam Adams 1:0, 2:0
Dave Davis 1-0, 1:1
Jim Jims 1_0 1_1
Tim Tims 0 0 0 1
Tom Toms 2-0, 3:2
Pet Peters 1 0 1 1
Sam Sams 1.o 1.1
Ace Aces 10 11
Abe Abes 1O 11
res = ['1', '0', 'o', 'O', '1', '1']
with open('txt_file.txt') as oldfile, open('new_txt.txt', 'w') as newfile:
for x in res:
for line in oldfile:
line_new = [x for x in res if (x in line)]
line = ''.join(line_new)
newfile.write(line)
新文件中的预期行
Dave Davis 1-0, 1:1
Jim Jims 1_0 1_1
Pet Peters 1 0 1 1
Sam Sams 1.o 1.1
Ace Aces 10 11
Abe Abes 1O 11
【问题讨论】:
-
明确更换规则
-
list文字中缺少逗号。 -
已编辑,粘贴和格式化时出错。
标签: python python-3.x list