如何让 Counter 将输入文本文件每一行的唯一单词的频率打印到输出文本文件的相应行?

How to get Counter to print frequency of unique words from each line of the input text file to the corresponding line on the output text file?

我有一道作业题。我应该编写一个名为 "WordsByLine" 的函数,它应该计算文件中每行的唯一单词的频率,并将唯一单词的频率打印到输出文件中的相应行。我的教授告诉我们输出应该是什么样子。例如,如果输入文本文件显示:

one fish two fish red fish blue fish

(一条鱼两条鱼是第一行,红鱼蓝鱼是第二行。)

输出必须如下所示:

two:1 one:1 fish:2 red:1 blue:1 fish:2

输出中的第一行是第一行唯一词的出现频率,第二行也是如此。

这是我的代码:

def wordsByLine(inFile, outFile):
    from collections import Counter
    outFile = open(outFile, 'w')
    with open(inFile, 'r') as f:
        freqs = Counter(f.readline().split())
    outFile.write(str(freqs))
    outFile.close()
print(wordsByLine('input.txt','output.txt'))

但这是我在文本文件中的输出。它只打印出第一行。:

Counter({'two':1, 'one':1, 'fish':2})

如何让计数器跳过一行并打印下一行(从输入文件的下一行)的唯一单词的频率?

正如评论中指出的那样,您只读过一行 f.readline。此外,您可能希望格式化文本而不是打印出 Counter 对象的字符串表示形式:

>>> from collections import Counter
>>> def words_by_line(infile, outfile):
...     with open(infile) as f1, open(outfile, 'w') as f2: 
...         for line in f1:
...             counts = Counter(line.split())
...             string_gen = ("{}:{}".format(k,v) for k,v in counts.items())
...             f2.write(" ".join(string_gen) + "\n")
... 
>>> words_by_line('input.txt','output.txt')

结果:

(trusty)juan@localhost:~$ cat output.txt 
fish:2 two:1 one:1
fish:2 red:1 blue:1
(trusty)juan@localhost:~$