如何使用Python计算文本文档中的非字母数字?

时间:2018-04-11 00:19:50

标签: python text document counting non-alphanumeric

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

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)

1 个答案:

答案 0 :(得分:4)

尝试

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)