【问题标题】:How to save a dictionary to a file with key values one per line?如何将字典保存到每行一个键值的文件中?
【发布时间】:2021-10-16 23:49:00
【问题描述】:

我希望文本是一个键:每行计数。 现在它将文件保存为普通字典,我无法弄清楚。

def makeFile(textSorted, newFile) :
dictionary = {}
counts = {}
for word in textSorted :
    dictionary[word] = counts
    counts[word] = counts.get(word, 0) + 1

# Save it to a file
with open(newFile, "w") as file :
    file.write(str(counts))
file.close()
return counts

【问题讨论】:

  • 你想要所有的 key:count 在不同的行吗?
  • 是的!一键:每行计数。

标签: python dictionary


【解决方案1】:

你可以这样用 CounterDict 和 csv 模块的几行代码:

import csv
def makeFile(textSorted, newFile) :
    from collections import Counter
    with open(newFile, "w") as f:
        wr = csv.writer(f,delimiter=":")
        wr.writerows(Counter(textSorted).items())

如果您只想存储键/值对,则使用两个字典毫无意义。单个 Counter dict 将获取所有单词的计数,而 csv.writerows 将写入每一对,以冒号分隔,每行一对。

【讨论】:

    【解决方案2】:

    试试这个

    def makeFile(textSorted, newFile) :
        counts = {}
        for word in textSorted :
            counts[word] = counts.get(word, 0) + 1
    
        # Save it to a file
        with open(newFile, "w") as file :
            for key,value in counts.items():
                file.write("%s:%s\n" % (key,value))
        return counts
    

    编辑:由于 iteritems 已从 python 3 中删除,因此将代码更改为 items()

    【讨论】:

    • 我收到此错误 - AttributeError: 'dict' object has no attribute 'iteritems'
    • 你在用python 3吗?
    • 使用 items() 而不是 iteritems() for python3 iteritems 在 python3 中被删除,并且 items 与 iteritems 在 python2 中所做的相同
    • 完美运行!谢谢!您能否也向我解释一下 %s 部分?我不熟悉它。
    • 使用with的重点是不需要关闭文件
    【解决方案3】:

    // 非常基本的字典到文件打印机

    dictionary = {"first": "Hello", "second": "World!"}
    
    with open("file_name.txt", "w") as file:
    
      for k, v in dictionary.items():
    
        dictionary_content = k + ": " + v + "\n"
    
        file.write(dictionary_content)
    

    【讨论】:

      【解决方案4】:
      x = open('a_file.txt','w')
      x.write('\n'.join(str(your_dict).split(', ')))
      x.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-30
        • 1970-01-01
        • 2014-11-11
        • 2013-10-12
        • 2018-06-02
        • 2019-11-18
        • 1970-01-01
        相关资源
        最近更新 更多