[英]Reading a text file and matching it to a dictionary key in python
I have a dictionary made in python. 我有一个用python编写的字典。 I also have a text file where each line is a different word.
我还有一个文本文件,其中每一行都是一个不同的单词。 I want to check each line of the text file against the keys of the dictionary and if the line in the text file matches the key I want to write that key's value to an output file.
我想根据字典的键检查文本文件的每一行,如果文本文件中的行与我想将该键的值写入输出文件的键匹配。 Is there an easy way to do this.
是否有捷径可寻。 Is this even possible?
这甚至可能吗? I am new to programming and cannot quite get a handle of how to access the dictionaries.
我是编程新手,无法完全掌握如何访问字典。 Thank-you for the help.
感谢您的帮助。
Read a file line by line like this: 像这样逐行读取文件:
with open(filename, 'r') as f:
for line in f:
value = mydict.get(line.strip())
if value is not None:
print value
This prints each value to standard output. 这会将每个值打印到标准输出。 If you want to output to a file it would be like this:
如果要输出到文件,它将是这样的:
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')
The following code has worked for me. 以下代码对我有用。
# 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.