读取文本文件并将其与python中的字典键进行匹配

时间:2013-03-02 21:24:01

标签: python text dictionary

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

2 个答案:

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

答案 1 :(得分:0)

以下代码对我有用。

# 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()