在Python中读取文本文件并与字典键匹配

0 投票
2 回答
9048 浏览
提问于 2025-04-17 17:43

我在Python中创建了一个字典。还有一个文本文件,里面每一行都是一个不同的单词。我想检查这个文本文件的每一行,看看它是否和字典里的键匹配。如果文本文件中的某一行和字典的键相同,我想把这个键对应的值写到一个输出文件里。有没有简单的方法可以做到这一点?这可能吗?我刚开始学编程,还不太明白怎么访问字典。谢谢你的帮助。

2 个回答

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

撰写回答