因此,我需要做的是在文件「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)
您可能想告訴我們您的文件中*是什麼,以及您如何期望這些內容在字典中使用。 – 2014-09-27 16:10:20
已更改我的答案... – Paul 2014-09-27 16:16:47