将计数器列表保存到 python 中的文件

Save a counter list to a file in python

我有这个,我想将计数器列表保存到文件中:

def main():
    #Ask for the input filename
    nameInput = input("Enter the name of the input file: ")

    #Open the file name that was specified
    filename = open(nameInput, 'r')

    #Read the file that was specified
    textFile = filename.read()

    #Get the word count in the file
    wordCount = (textFile.split())

    #Print out the word count
    print("There are",len(wordCount),"words in this file.")

    #Import the Counter module
    from collections import Counter

    #Get the frequency of every word in the file
    freq = Counter(wordCount)

main()

如何将 "freq" 字符串保存到文件中?

只需在 w 写入模式下打开另一个文件,然后将变量 freq 的值写入该文件。

def main():
    #Ask for the input filename
    nameInput = input("Enter the name of the input file: ")

    #Open the file name that was specified
    filename = open(nameInput, 'r')

    #Read the file that was specified
    textFile = filename.read()

    #Get the word count in the file
    wordCount = (textFile.split())

    #Print out the word count
    print("There are",len(wordCount),"words in this file.")

    #Import the Counter module
    from collections import Counter

    #Get the frequency of every word in the file
    freq = Counter(wordCount)
    with open('outfile', 'w') as w:
        w.write("The word frequency is " + str(freq))
    filename.close()

main()