2014-09-27 48 views
-2

因此,我需要做的是在文件「clues.txt」中讀取並將其存儲到字典中......到目前爲止,我已經將它存儲到列表中,但是掙扎字典做...如何將文件讀入字典

我的代碼讀取到一個列表,如圖所示...

def read_clues(clues): 
#TRYS TO OPEN THE FILE "CLUES.TXT"  
    try: 
     readclues = open("clues.txt","r") 
     for line in readclues: 
#SAME CODE AS TASK ONE HOWEVER THIS TIME IT IS DOING IT FOR CLUES 
      clues.append(line[:len(line)-1]) 

     for clue in clues: 
      print(clue) 
     readclues.close() 
     return clues 
#IF THE FILE CANNOT BE FOUND IT WILL PRINT "ERROR FINDING FILE" 
    except: 
     print("Error finding file") 

那麼什麼是在文件線索如下所示的字母和符號配對。 ...

A# 
M* 
N% 

下一部分我的程序涉及字典。基本上它是取代words.txt文件(如下圖所示),並替換它內部的線索對...演示如下所示...

words.txt作爲列表讀入,因爲它應該是...

#+/084&" 
#3*#%#+ 
8%203: 
,1$& 
!-*% 
.#7&33& 
#*#71% 
&-&641'2 
#))85 
9&330* 

clues.txt被讀入作爲目前一個列表,但需要被讀取的字典...

A+/084&" 
A3MA%A+ 
8%203: 
,1$& 
!-M% 
.A7&33& 
AMA71% 
&-&641'2 
A))85 
9&330 

線索項目都得到了在改爲。 txt ...

該代碼,這是...但是這需要讀入一個字典時被改變......

#SUBSTITUTE THE LETTERS WITH SYMBOLS FROM THE CLUES 
def replace_symbols(clues, words): 
#SPLITS THE CLUES SO THAT THEY CAN BE REPLACED WITH THE LETTER 

    for clue in clues: 
     letter = clue[0] 
     symbol = clue[-1] 

     for index in range(len(words)): 
#LOOPS THROUGH THE LIST TO FIND AN INDEX VALUE 
      words[index] = words[index].replace(symbol,letter) 
#RETURNS THE NEW COPY BACK TO THE ORIGINAL LIST 
    return words 

我正努力但從接收錯誤代碼......

def read_clues(clues): 
    d = {} 
    with open("clues.txt") as f: 
     for line in f: 
      (key, val) = line[1], line[0] 
      d[key] = val 


def replace_symbols(clues, words): 
    for word in range(len(words)): 
     for key, value in d.items(): 
      words[word] = words[word].replace(key, value) 
+0

您可能想告訴我們您的文件中*是什麼,以及您如何期望這些內容在字典中使用。 – 2014-09-27 16:10:20

+0

已更改我的答案... – Paul 2014-09-27 16:16:47

回答

1

試試這個它會根據線索的模式工作文件,你貼:

d = {} 
with open("file.txt") as f: 
    for line in f: 
     (key, val) = line[1], line[0] 
     d[key] = val 

試試這個讀字典鍵值對和更換符號:

for word in range(len(words)): 
    for key, value in d.items(): 
     words[word] = words[word].replace(key, value) 

編輯:

d = {} 
def read_clues(clues): 
    global d 
    with open("hey.txt") as f: 
     for line in f: 
      (key, val) = line[1], line[0] 
      d[key] = val 


def replace_symbols(clues, words): 
    global d 
    for word in range(len(words)): 
     for key, value in d.items(): 
      words[word] = words[word].replace(key, value) 

只是把這個代碼在一個.py文件並運行它,它會工作。你正在做的是你試圖調用一個局部變量d以外的範圍,這就是爲什麼你現在得到這個錯誤,我已經使這個d變量全局。

#REPLACES LETTERS 
print("======== The clues have been replaced ===========") 
replace_symbols(clues, words) 
for key, value in d.items(): 
    print key, value #This will print the symbols and letters 
+0

在打印後得到語法錯誤... – Paul 2014-09-28 19:50:28

+0

嘗試重新排列似乎無法修復它... – Paul 2014-09-28 19:54:13

+0

你能爲我看看這個嗎? – Paul 2014-09-28 20:03:00