【问题标题】:Reading a text file and matching it to a dictionary key in python读取文本文件并将其与 python 中的字典键匹配
【发布时间】:2013-03-02 21:24:01
【问题描述】:

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

【问题讨论】:

    标签: python text dictionary


    【解决方案1】:

    像这样逐行读取文件:

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

    【讨论】:

    • 谢谢。效果很好。非常感激。我知道这些问题很简单,但对学习过程很有帮助。
    【解决方案2】:

    以下代码对我有用。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 2016-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多