如何将字典保存到每行一个键值的文件中?

2024-10-01 07:49:41 发布

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

我希望文本是一个键:计数行。 现在它把文件保存成一个普通字典,我搞不懂。在

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

Tags: 文件in文本forgetdictionary字典def
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)

您可以这样做,这是几行,其中有一个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())

如果只想存储键/值对,那么使用两个字典是没有意义的。一个单独的计数器dict将得到所有单词和csv.writerows将每一对用冒号隔开,每行一对。在

试试这个

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是从python3中删除的,所以将代码改为items()

相关问题 更多 >