如何计算带有 Python 的文本文档中的非字母数字?

How do I count non alphanumerics in a text document with Python?

这是我的代码。我无法弄清楚如何让我的程序计算非字母数字。我是一名新的编码学生,所以对我放轻松。

infile = open("Gettysburg.txt", "r")
data = infile.readlines()
non_alpha_num = 0
uppercase_count = 0
lowercase_count = 0
whitespace_count = 0
digit_count = 0
for character in data:
    if character.isupper():
        uppercase_count += 1
    elif character.islower():
        lowercase_count += 1
    elif character.isspace():
        whitespace_count +=1
    elif character.isdigit():
        digit_count +=1
    if not character.isalnum() and not character.isspace():
        non_alpha_num += 1
    print("Jake's text document counter")
    print('The uppercase count is ', uppercase_count)
    print('The lowercase count is ', lowercase_count)
    print('The digit count is ', digit_count)
    print('The whitespace count is ', whitespace_count)
    print('The non alphanumeric count is ', non_alpha_num)

尝试

if not character.isalnum():
    non_alpha_num += 1

排除空格:

if not character.isalnum() and not character.isspace():
    non_alpha_num += 1

编辑:关注@ShadowRanger 评论: 你不是在读字,你是在读台词。请修改您的代码。

infile = open("Gettysburg.txt", "r")
data = infile.readlines()

uppercase_count=0
lowercase_count=0
whitespace_count=0
digit_count=0
non_alpha_num=0

for line in data:
    for character in line :
        if character.isupper():
            uppercase_count += 1
        elif character.islower():
            lowercase_count += 1
        elif character.isspace():
            whitespace_count +=1
        elif character.isdigit():
            digit_count +=1
        elif not character.isalnum() and not character.isspace():
            non_alpha_num += 1


print("Jake's text document counter")
print('The uppercase count is ', uppercase_count)
print('The lowercase count is ', lowercase_count)
print('The digit count is ', digit_count)
print('The whitespace count is ', whitespace_count)
print('The non alphanumeric count is ', non_alpha_num)