使用参考值修改文本文件

时间:2013-11-21 20:57:11

标签: python

我有以下参考数据,如

21   1
32   2
45   3

并且有一个文本文件(file.txt)包含两个或更多列,如

21  32  45
45  21  32
32  45  21

我想使用像

这样的参考值来更改file.txt
1   2   3
3   1   2
2   3   1

如您所见,参考文件21,32和45相等,分别与数字1,2和3匹配。

我基于两个for循环编码并比较了两个值。

with open('ref') as f1, open('file.txt') as f2, open('out.txt', 'w') as f3:

     for lines in f1:
         value1 = lines.split()

         for line in f2:
             if value2 == value1[0]:
                value2 = value1[1]
                line = ' '.join(value2) + '\n'
             f3.write(line)

没有任何改变。怎么能这样做呢?

3 个答案:

答案 0 :(得分:1)

你没有比较正确

with open('ref') as f1, open('file.txt') as f2, open('out.txt', 'w') as f3:

 for lines in f1:
     value1 = lines.split()

     for line in f2:
         value2 = line.split() # value2 is a list
         if value2 == value1[0]: # if a list is equals to a value => always false
            value2 = value1[1]
            line = ' '.join(value2) + '\n'
         f3.write(line) # so line is still the original line since the if statement is always false

答案 1 :(得分:1)

mydict = {}
with open('ref') as f1:
    for line in f1:
        key, value = line.split()
        mydict[key] = value

with open('file.txt') as f2, open('out.txt', 'w') as f3:
    for l in f2:
        line = l.split()
        newline = ''
        for item in line:
            newline += mydict[item] + " "
        f3.write(newline + "\n")

答案 2 :(得分:1)

您需要第三个循环来迭代file.txt的列。像

这样的东西
for line in f2:
    value2 = line.split()
    for item in value2:
        if item == value1[0]:
            value2 = value1[1]

dict似乎很适合你的问题:

#/usr/bin/env python
ref = {}
with open("ref") as file:
    for line in file:
        k, v = line.split()
        ref[k] = v

with open("file.txt") as file, open("res", 'w') as res:
        for line in file:
            for item in line.split():
                res.write("%s\t" % ref[item])
            res.write("\n")