Python 将字典写入文本文件

Python 将字典写入文本文件,python,text,dictionary,save,writing,Python,Text,Dictionary,Save,Writing,以下是我的代码: def byFreq(pair): return pair[1] def ratio(file): #characterizes the author and builds a dictionary text = open(file,'r').read().lower() # text += open(file2,'r').read().lower() # text += open(file3,'r').read().lower()

以下是我的代码:

def byFreq(pair):
    return pair[1]

def ratio(file):
    #characterizes the author and builds a dictionary
    text = open(file,'r').read().lower()
    # text += open(file2,'r').read().lower()
    # text += open(file3,'r').read().lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
        text = text.replace(ch, ' ')
    words = text.split()

    "construct a dictionary of word counts"
    counts = {}
    wordNum = 0
    for w in words:
        counts[w] = counts.get(w, 0) + 1
        wordNum = wordNum + 1
    # print ("The total number of words in this text is ",wordNum)

    "output analysis of n most frequent words"
    n = 50
    items = list(counts.items())
    items.sort()
    items.sort(key=byFreq, reverse=True)

    # print("The number of unique words in", file, "is", len(counts), ".")
    r = {}
    for i in range(n):
        word, count = items[i]

        "count/wordNum = Ratio"
        r[word] = (count/wordNum)
    return r




def main():
    melvile = ratio("MelvilleText.txt")
    print(melvile)
    outfile = input("File to save to: ")
    text = open(outfile, 'w').write()
    text.write(melvile)

main()
我不断得到以下错误:

Traceback (most recent call last):
  File "F:/PyCharm/Difficult Project Testing/dictionarygenerator.py", line 48, in <module>
    main()
  File "F:/PyCharm/Difficult Project Testing/dictionarygenerator.py", line 43, in main
    text = open(outfile, 'w').write()
TypeError: write() takes exactly 1 argument (0 given)

有谁能告诉我我做错了什么,以及如何修复它,因为我无法理解它。非常感谢您的帮助。

您有两个问题

首先,你第一次打电话给write时没有写任何东西。只需要打一次电话

text = open(outfile, 'w')
text.write(melvile)
打开文件进行写入后,需要告诉文本对象要写入什么

其次,梅尔维尔不是一根弦。如果只想将值打印到文本文件中,则可以打印字典

text = open(outfile, 'w')
for key in melville:
    text.write("%s: %f\n", key, melville[key])

另一个答案是关于空文的。text=openoutfile“w”。write应该是text=openoutfile“w”。下一个问题是dict不能直接写入文件,它们需要以某种方式编码成字符串或二进制表示

有很多方法可以做到这一点,但有两个流行的选项是pickle和json。两者都不是为人类读者准备的

import pickle

... all of your code here

with open(outfile, 'w') as fp:
    pickle.dump(melville, fp)

首先,删除不带参数的写操作。那是你犯错误的原因

其次,您必须关闭您的文件。添加文本。关闭


第三,“melvile”不是字符串。如果您想以最简单的方式将其转换为字符串,请使用strmelville。这会将其转换为字符串,如您可以查看是否打印Melvile。

关于空写入,您是对的,但它仍然不起作用,因为Melvile不是字符串。当我这样做时,它会告诉我预期的类型“byte | bytearray”谢谢!你真的救了我!
import json

... all of your code here

with open(outfile, 'w') as fp:
    json.dump(melville, fp)
text = open(outfile, 'w').write()
text.write(melvile)