0

我有一本用python制作的字典。我还有一个文本文件,其中每一行都是一个不同的单词。我想根据字典的键检查文本文件的每一行,如果文本文件中的行与我想将该键的值写入输出文件的键匹配。是否有捷径可寻。这甚至可能吗?我是编程新手,无法完全掌握如何访问字典。感谢您的帮助。

4

2 回答 2

2

像这样逐行读取文件:

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')
于 2013-03-02T21:28:34.697 回答
1

以下代码对我有用。

# 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()
于 2016-07-17T02:29:10.927 回答