簡體   English   中英

如何獲取計數器以從輸入文本文件的每一行到輸出文本文件的相應行上打印唯一單詞的頻率?

[英]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:~$ 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM