【问题标题】:Count specific character in text file计算文本文件中的特定字符
【发布时间】:2013-06-28 03:12:31
【问题描述】:

如何计算特定字符(非空格)在文本文件中出现的次数? (即“,”“。”“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: ")

到目前为止的分发代码

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)

这为我提供了我想要的 a 和 b 输出,但为每个字符编写每一行代码效率不高。我将如何遍历每个可能的字符,然后打印出计数?

【问题讨论】:

    标签: python-3.x count character text-files


    【解决方案1】:

    使用collections.Counter

    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))
    

    【讨论】:

    • 这没有给我正确数量的文本文件的单个字符。我是否需要创建一个新变量,在初始化计数之前删除所有空格?
    • @EduardoVasquez,预期的输出是什么,你得到了什么?
    • @EduardoVasquez,你想让'a'和'A'都算作'a'吗?
    • 是的,这就是我在初始化 for 循环之前使用 .lower() 的原因
    • 效果很好!我将如何对字符进行排序?我希望它显示 , 和 .首先,然后按字母升序从a -z
    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多