Python 3.x 对文本文件中的特定字符计数

Python 3.x 对文本文件中的特定字符计数,python-3.x,count,character,text-files,Python 3.x,Count,Character,Text Files,如何计算特定字符(非空白)在文本文件中出现的次数?(即“a”、“k”、“m”) 以下是我到目前为止的情况: file = open("filename.txt","r") num_char = 0 num_words = 0 num_lines = 0 for line in file: words = line.split() num_lines += 1 num_words += len(words) num_char += len(line) p

如何计算特定字符(非空白)在文本文件中出现的次数?(即“a”、“k”、“m”)

以下是我到目前为止的情况:

file = open("filename.txt","r")

num_char = 0
num_words = 0
num_lines = 0


for line in file:
    words = line.split()
    num_lines += 1
    num_words += len(words)
    num_char += len(line)



print ("Character count:\t" + str(num_char))
print ("Word count:\t\t" + str(num_words))
print ("Line count:\t\t" + str(num_lines))
print ("Distribution of characters: ")
迄今为止的分发代码 这为a和b提供了所需的输出,但为每个字符编写每行代码的效率不是很高。如何循环查找每个可能的字符,然后打印出计数?

使用


这并没有为文本文件提供正确的单个字符数。我是否需要创建一个在初始化计数之前删除所有空格的新变量?@EduardoVasquez,预期的输出是什么,您得到了什么?@EduardoVasquez,您是否希望“a”和“a”都计算为“a”?是的,这就是为什么我在初始化for loopWorks之前使用.lower()!我将如何对字符进行排序?我想让它显示,和。首先,然后按字母顺序从a到z升序排列
text = file.read()
file.close()
words = text.strip()
final = words.lower()
for i in range(len(words)):
    first = final.count("a")
    second = final.count("b")
print (first)
print (second)
from collections import Counter

file = open("filename.txt", "r")

num_char = 0
num_words = 0
num_lines = 0
char_distribution = Counter()

for line in file:
    words = line.split()
    num_lines += 1
    num_words += len(words)
    num_char += len(line)
    char_distribution += Counter(line.lower())

print("Character count:\t{}".format(num_char))
print("Word count:\t\t{}".format(num_words))
print("Line count:\t\t{}".format(num_lines))
print("Distribution of characters: ")
for char, count in sorted(char_distribution.items()):
    if char.isalpha() or char in ',.':
        print("\t{}\t\t{}".format(char, count))