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

2024-10-05 11:25:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本Python词典。我还有一个文本文件,其中每一行是一个不同的词。我想对照字典的键检查文本文件的每一行,如果文本文件中的行与键匹配,我想将该键的值写入输出文件。有什么简单的方法可以做到这一点吗。这可能吗?我对编程还不太熟悉,无法很好地掌握如何访问词典。谢谢你的帮助。


Tags: 文件方法字典编程词典文本文件行与键
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')

以下代码对我有效。

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

相关问题 更多 >

    热门问题