【问题标题】:Reading a text file and replacing it to value in dictionary读取文本文件并将其替换为字典中的值
【发布时间】:2020-11-15 17:53:57
【问题描述】:

我有一本用 python 制作的字典。我还有一个文本文件,其中每一行都是一个不同的单词。我想根据字典的键检查文本文件的每一行,如果文本文件中的行与我想将该键的值写入输出文件的键匹配。是否有捷径可寻。这甚至可能吗?

例如,我正在这样读取我的文件:

test = open("~/Documents/testfile.txt").read()

对其进行标记,对于每个单词标记,我都想在字典中查找,我的字典设置如下:

dic = {"a": ["ah0", "ey1"], "a's": ["ey1 z"], "a.": ["ey1"], "a.'s": ["ey1 z"]}

如果我在文件中遇到'a' 字母,我希望它输出["ah0", "ey1"]

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    你可以试试:

    for line in all_lines:
        for val in dic:
            if line.count(val) > 0:
                print(dic[val])
    

    这将查看文件中的所有行,如果该行包含来自 dic 的字母,那么它将在字典中打印与该字母关联的项目(您必须执行 all_lines = test.readlines() 之类的操作才能获取所有列表中的行)dic[val] 将列表与值 ["ah0", "ey1"] 关联,因此您不仅需要打印它,还可以在其他地方使用它

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      #dictionary to match keys againts words in text filee
      dict = {"a": ["ah0", "ey1"], "a's": ["ey1 z"], "a.": ["ey1"], "a.'s": ["ey1 z"]}
      
      # Read from text filee
      open_file = open('sampletext.txt', 'r')
      lines = open_file.readlines()
      open_file.close()
      
      #search the word extracted from textfile, if found in dictionary then print list into the file
      for word in lines:
          if word in dict:
              write_to_file = open('outputfile.txt', 'w')
              write_to_file.writelines(str(dict[word]))
              write_to_file.close()
      

      注意:如果您读取的文本文件有多行,您可能需要去掉换行符“\n”

      【讨论】:

        猜你喜欢
        • 2016-04-11
        • 1970-01-01
        • 2013-08-16
        • 2013-03-14
        • 1970-01-01
        • 2021-10-04
        • 2013-07-20
        • 2011-10-02
        • 1970-01-01
        相关资源
        最近更新 更多