2017-07-27 23 views
-1

我正在計算文本文件中的元素。我知道我錯過了一個顯而易見的部分,但我無法把它放在手指上。這是我目前有剛剛產生的字母數「F」不是文件:如何計算文本文件中的元素?

filename = open("output3.txt") 
f = open("countoutput.txt", "w") 
import collections 
for line in filename: 
    for number in line.split(): 
     print(collections.Counter("f")) 
     break 
+0

你可以分享你的文件的樣本?你也可以計算每行「f」字母的數量;你想在所有的文件中有「f」的總數? – MedAli

+0

化學元素? – nbro

回答

2
import collections 

counts = collections.Counter() # create a new counter 
with open(filename) as infile: # open the file for reading 
    for line in filename: 
     for number in line.split(): 
      counts.update((number,)) 
      print("Now there are {} instances of {}".format(counts[number], number)) 
print(counts) 
+4

一些評論或解釋行可能會很長一段時間,對於一個顯然是新的Python用戶.. – Aaron

+0

@Aaron我從來沒有使用計數器功能 –

+0

@ H.Minear這對所有其他人都有好處問題也是如此,即使你只是通過閱讀代碼就能理解.. – Aaron