2015-10-14 129 views
0

我已經從一個文本文件中創建了一個字典,並希望用它來替換出現在單獨文件中的值與它們的值。用值替換字典鍵

例如,我的字典裏看起來像......

names = {1:"Bob", 2:"John", 3:"Tom"} 

而其他文件看起來像......

1 black cat 
2 gray elephant 
3 brown dog 

我希望它最終被...

Bob black cat 
John gray elephant 
Tom brown dog 

到目前爲止,我只寫了代碼來製作字典

names = {} 
for line in open("text.txt", 'r'): 
    item = line.split() 
    key, value = item[0], item[2] 
    names[key] = value 

我想打開第二個文件並使用名稱字典來替換出現在那裏的鍵和它們的值。我看到你可以使用replace(key, dict[key])但我不知道如何。

+0

你試過json模塊,它是乾淨多了。例如: import json json.load(file_object),它會轉換成一個python字典,然後你可以使用遞歸做替換 – reticentroot

+0

海報並沒有表明她的數據格式是在json中。根據她分解數據的方式來判斷,事實並非如此。 – Dan

回答

0

你可以通過字典值迭代,並使用replace

for key in names: 
    text = text.replace(key, names[key]) 

(作爲text文件的內容)

+0

我想我可以直接像這樣使用它,但它會拋出一個屬性錯誤,即'文件'對象沒有屬性'replace'。同樣的事情,如果我使用f.splitlines()只有它的'列表'沒有屬性'替換'。 –

+0

這是因爲'text'必須是一個字符串。在上面的代碼之前使用'text = f.read()'! – cdonts

2

如果您使用的字典,我會加載它們分成兩個獨立字典,然後合併它們。

如果您已經加載名字爲names和動物進入animals,你可以像這樣把它們合併:

merged = {} 
for key, name in names.iteritems(): 
    merged[name] = animals[key] 
0

這裏有一種方法:

my_dict = {1:"Bob", 2:"John", 3:"Tom"} 

with open("test.txt", "r") as f_in, open("new.txt", "w") as f_out: 
    for line in f_in: 
     s_line = line.split() 
     new_line = [my_dict[int(s_line[0])]] 
     new_line.extend(s_line[1:]) 
     f_out.write(" ".join(new_line) + "\n") 
0
mydict = {1:"Bob", 2:"John", 3:"Tom"} # this is already a dicionary so do nothing 
mydict2 = {} 
myfile = """1 black cat 
2 gray elephant 
3 brown dog 
""" 


# you should use with open(file, 'r') as data: --> fyi 

# convert the file to a dictionary format 
for line in myfile.split('\n'): 
    chunks = line.split(' ') 
    if chunks != ['']: # i needed this because of the some white space in my example 
    key, value = chunks[0], chunks[1] + ' ' + chunks[2] 
    mydict2[key] = value 

# remember dictionaries are not sorted, so there is no guarantee things will 
# match as you expect, however there is plenty of documentation 
# that you can follow to sort the dictionary prior to what i'm doing below 
# i'm assuming that there are always the same number of items in both dictionaries 
new_dict = {} 
new_values = mydict2.values() # create a list of all the values 
# iterate over the dictionary item 
index = 0 
for k, v in mydict.items(): 
new_dict[v] = new_values[index] # append the value of the first dictionary with the value from the list 
index += 1 

print new_dict 
0

你可以直接寫入一個新的文件並重定向到names
您還需要切片行的其餘部分(item[2]只獲得第3元),並加入他們一起回來:

names = {1:"Bob", 2:"John", 3:"Tom"} 
with open("text.txt", 'r') as r, open('out.txt', 'w') as w: 
    for line in fp: 
     item = line.split() 
     key, value = item[0], item[1:] # Python 2 
     # key, *value = item    # Python 3 
     w.write("{} {}".format(names[int(key)], ' '.join(value))) 

$ cat out.txt 
Bob black cat 
John gray elephant 
Tom brown dog