因此,我需要做的是在文件“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