2016-09-23 58 views
1

創建內容的文件:讀取文件和prduce分類詞典

Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5 

閱讀本文件並創建一個字典,float類型的,即,詞典的項目類型的元組的密鑰和值應看起來像這樣:

(‘Mary’,’Jane’) : 5.8 

將此字典轉換爲元組列表。按降序對它們進行排序並打印出來。

我的代碼是:

作爲字符串字典的
f = open('sam.txt', 'r') 
answer = {} 
tuple(answer.keys()) 
for i in answer: 
    print tuple(answer.keys()) 
for line in f: 

    k, v = ((line.strip()).split(':')) 
    answer[((k.strip()))] = float(v.strip()) 
print answer  
c = answer.items() 
d = sorted(c) 
print tuple(reversed(sorted(c))) 
f.close() 

在這裏我得到鑰匙的規定並不元組,請告訴我,我的錯誤,請做一些微調,以我的有關問題。

+1

爲什麼在顯式爲空時對答案字典執行操作? –

+0

你不使用'd',因此你排序兩次。順便說一句,而不是'顛倒(排序(c))''你可以做'排序(c,反向= True)'。 – swenzel

+0

我被要求使用reverse()函數,所以我嘗試那樣 –

回答

0

你也應該上逗號分割','鍵和不僅

answer[tuple(k.strip().split(','))] = float(v.strip()) 

在一個側面說明,你並不需要,最初的字典特技代碼:

answer = {} 
with open('sam.txt') as f: # open with context manager does auto close 
    for line in f: 
     k, v = line.strip().split(':') 
     answer[tuple(k.strip().split(','))] = float(v.strip()) 
+0

謝謝,我從中學到了一些東西 –

0

如果你有像這樣的新行數據:

Mary,Jane : 5.8 
Mary,Doe : 6.0 
John,Doe : 6.3 
John,Muller : 5.6 
Mary,Muller : 6.5 

,然後將代碼如下:

f = open('data.txt', 'r') 
answer = {} 
for line in f: 
    k, v = ((line.strip()).split(':')) 
    key1, key2 = k.split(',') 
    answer[(key1, key2)] = float(v.strip()) 

print answer 
c = answer.items() 
d = sorted(c) 
print tuple(reversed(sorted(c))) 
f.close() 
+0

Thank you its helpful –

0

我沒有回答這樣我可以知道是否有任何進一步的升級需要它,使之更有效

f = open('sam.txt') 
answer = {tuple(x.split(':')[0].strip().split(',')): float(x.split('[1].strip()) for x in f} 
print "\ndictionary taken from file is:\n" 
print answer  
c = answer.items() 
d = sorted(c) 
print "\nafter sorted and converted into tuples the output is:\n" 
print tuple(reversed(sorted(c))) 
f.close() 
0

內置功能通常很有用,但有時您只需要一個簡單的正則表達式:

# Generate file 
txt = "Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5" 
with open("out.txt","w+") as FILE: FILE.write(txt) 

# Read file and grab content 
content= [ re.findall(r"([A-Za-z]+),([A-Za-z]+)\s:\s([0-9]\.[0-9])",line) for line in tuple(open("out.txt","r")) ] 

# Make dictionary 
dct = {(k1,k2):float(v) for (k1,k2,v) in reduce(lambda x,y: x+y, content)} 
print(dct)