2017-10-06 139 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() - 如果需要整个文件的副本。
按照百分比文件大小除以命中数。

正则表达式也将处理您的案例问题。

相关问题