0
我有一個用python編寫的字典。我也有一個文本文件,每行是不同的單詞。我想根據字典的鍵檢查文本文件的每一行,並且如果文本文件中的行與我想將該鍵的值寫入輸出文件的鍵匹配。是否有捷徑可尋。這甚至有可能嗎?我是編程新手,無法完全掌握如何訪問字典。感謝您的幫助。讀取文本文件並將其與Python中的字典鍵相匹配
我有一個用python編寫的字典。我也有一個文本文件,每行是不同的單詞。我想根據字典的鍵檢查文本文件的每一行,並且如果文本文件中的行與我想將該鍵的值寫入輸出文件的鍵匹配。是否有捷徑可尋。這甚至有可能嗎?我是編程新手,無法完全掌握如何訪問字典。感謝您的幫助。讀取文本文件並將其與Python中的字典鍵相匹配
逐行讀取一個文件中的行是這樣的:
with open(filename, 'r') as f:
for line in f:
value = mydict.get(line.strip())
if value is not None:
print value
這將打印的每個值到標準輸出。如果你想輸出到一個文件,它會是這樣的:
with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile:
for line in infile:
value = mydict.get(line.strip())
if value is not None:
outfile.write(value + '\n')
以下代碼已經爲我工作。
# Initialize a dictionary
dict = {}
# Feed key-value pairs to the dictionary
dict['name'] = "Gautham"
dict['stay'] = "Bangalore"
dict['study'] = "Engineering"
dict['feeling'] = "Happy"
# Open the text file "text.txt", whose contents are:
####################################
## what is your name
## where do you stay
## what do you study
## how are you feeling
####################################
textfile = open("text.txt",'rb')
# Read the lines of text.txt and search each of the dictionary keys in every
# line
for lines in textfile.xreadlines():
for eachkey in dict.keys():
if eachkey in lines:
print lines + " : " + dict[eachkey]
else:
continue
# Close text.txt file
textfile.close()
感謝信。它效果很好。非常感激。我知道這些都是簡單的問題,它在學習過程中非常有幫助。 – 2013-03-02 21:36:24