如何将文件读入字典

时间:2014-09-27 16:08:45

标签: python list dictionary

所以我需要做的是读取文件“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

然后在words.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)

1 个答案:

答案 0 :(得分: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