Python txt 文件中的多对替换

Python multiple pairs replace in txt file

我有 2 个 .txt 文件,第一个是这样组织的:

1:NAME1
2:NAME2
3:NAME3
...

第二个像这样:

1
1
1
2
2
2
3

我想要做的是根据 .txt 1 中的对替换 .txt 2 中的每一行,如下所示:

NAME1
NAME1
NAME1
NAME2
NAME2
NAME2
NAME3

有办法吗?我想组织第一个 txt 删除 1: 2: 3: 并将其作为数组读取,然后在范围内为 i 循环(1,txt 1 中的行数)然后在 txt 2 中找到包含的行"i" 并替换为数组的第 i 个元素。但是我当然不知道该怎么做。

这应该可以解决问题。它读取第一个文件并将 k, v 对存储在字典中。该字典用于为您在第二个文件中找到的每个 k 输出 v

但是......如果你想防止这些反对票,最好post你自己的代码片段来展示你已经尝试过的......现在你的问题是一个红色毯子成群结队的 SO'ers 对所有没有代码的东西投反对票。该死,他们甚至对答案投反对票,因为问题中没有代码...

lookup = {}
with open("first.txt") as fifile:
    for line in fifile:
        lookup[line.split[":"][0]] = line.split[":"][1] 

with open("second.txt") as sifile:
    with open("output.txt", "w") as ofile:
        for line in sifile:
            ofile.write("{}\n".format(lookup[line])

正如罗德里戈评论的那样。有很多方法可以实现它,但是将名称存储在字典中可能是可行的方法。

# Read the names
with open('names.txt') as f_names:
    names = dict(line.strip().split(':') for line in f_names)

# Read the numbers
with open('numbers.txt') as f_numbers:
    numbers = list(line.strip() for line in f_numbers)

# Replace numbers with names
with open('numbers.txt', 'w') as f_output:
    for n in numbers:
        f_output.write(names[n] + '\n')