2017-10-06 34 views
-7

我怎樣才能計算一個txt文件的第一行有多少「a」。第二次等多少次?以及如何計算整個文件中一個字母的百分比?我知道如何在一個字符串中做到這一點,但沒有把它放在一個文件中,逐行... sry im nooob ,,,,計算一個字母出現在txt文件的一行中的次數。在python 2.3

+2

Python 2.3?真?無論如何:你有什麼嘗試? – vaultah

+1

2k17中的Python-2.3? – shash678

+0

[計算字符串中字符出現次數]可能的重複(https://stackoverflow.com/questions/1155617/count-occurrence-of-a-character-in-a-string) – ptyyy

回答

0

如果我正確理解你的問題,像這樣的工作:

read_lines = open("as.txt", "r") #this opens and reads the entire file 

line_number = 1 #setting a var to the line number we're at 

for word in read_lines: #starts looping for each word in the line 
    number_of_as = 0 #we are going to keep track of all the a's here for each line 
    for letter in word: #for each letter in each word in the line 
     if letter == "a" or letter == "A": #if the letter is a a or A 
      number_of_as += 1 #add 1 to how many a's are in this line 
    print("Line " + str(line_number) + " has " + str(number_of_as) + " a's") 
    line_number += 1 #now we move to the next line so we add 1 to our tracker 

這將讀取整個文件,到每個字的文件中,並檢查每個字母。如果這封信是a,那麼計數器number_of_as增加1。在程序結束時,將顯示總數a

但是,這是用python 3編寫的。

現在的代碼顯示了每行a的數量。

+0

即時通訊不知道它是否會在Python 2中工作,但我會嘗試。非常感謝 ! –

+0

請讓我知道它是否工作。 – GreenSaber

+0

但如何將它逐行排列?我的意思是如何得到第一行有多少「a」和第二行有多少?再次感謝你!欣賞它。 –

0

c.f.正則表達式docs

對於一個快速和骯髒的解決方案,我會在每個字符串上使用re.subn() - 如果需要整個文件的副本。
按照百分比文件大小除以命中數。

正則表達式也將處理您的案例問題。

相關問題