【问题标题】:Python multiple pairs replace in txt filePython多对替换txt文件
【发布时间】:2015-05-27 21:16:15
【问题描述】:

我有 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 in range(1, number of lines in txt 1) 循环,然后在 txt 2 中找到包含的行"i" 并替换为数组的第 i 个元素。但是我当然不知道该怎么做。

【问题讨论】:

  • 只在字典中存储文件 1 的记录,文件 2 有 dict 的键,你应该用值替换,即 dict[key]

标签: python text substitution


【解决方案1】:

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

# 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')

【讨论】:

    【解决方案2】:

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

    但是....如果您想防止这些反对意见,最好发布您自己的代码 sn-p 以显示您尝试过的内容...现在您的问题是 SO 部落的红毯那些对其中没有代码的所有内容都投反对票的人。见鬼,他们甚至对答案投了反对票,因为问题中没有代码......

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

    【讨论】:

    • 没有试过你的,但是 jrmyp 的代码运行良好。不知道人们对这种投票有什么问题,我有一个想法,但不知道如何编码,这就是我在这里问的原因!顺便谢谢你
    猜你喜欢
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 2022-01-27
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多