2013-11-21 60 views
0

修改文本文件I具有以下參照數據等使用基準值

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和45e分別符合數字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) 

什麼都沒有改變。這怎麼可能呢?

+2

什麼是你'value2'? –

+0

對不起,如果value2 == value [0]有缺少:有value2 = line.split() –

+0

對不起,輸出是什麼?基本上你想做什麼? – JadedTuna

回答

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") 
+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 
+0

我不明白爲什麼「總是虛假」。正如我在我的代碼中所理解的那樣,value1 [0]是21,那麼如果value2中的任何數字等於此數字(21),則將value2數字替換爲value1 [1]。 –

+1

你沒有比較列表與數字,'[1,2,3] == 3'總是假的,你應該在[1,2,3]中做'3而不是 – JoeC

1

您需要第三個循環來遍歷的file.txt列。像

for line in f2: 
    value2 = line.split() 
    for item in value2: 
     if item == value1[0]: 
      value2 = value1[1] 

一個字典的東西似乎是一個不錯的選擇你的問題:

#/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") 
+1

謝謝你對這個問題的評論。 –

+0

我很欣賞糾正我的代碼。 –