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