【问题标题】:How do I count non alphanumerics in a text document with Python?如何使用 Python 计算文本文档中的非字母数字?
【发布时间】:2018-09-20 17:18:24
【问题描述】:

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

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)

【问题讨论】:

  • 我可以让我的程序计算并显示数字、大写等的数量,但我不知道如何计算非字母数字字符。
  • 您可以尝试使用 in 运算符引用非字母数字字符数组,但似乎任何未通过这些测试之一的字符默认情况下都是非字母数字集的一部分,这基本上就是 Sruthi 所说的。
  • 这可能是一个复制粘贴问题,但你有一个缩进问题:最后一个 elif 中的代码应该缩进。 (如果这些印刷品不应该在 elif 中,那么您有一个空的 elif,这也是一个问题。)
  • 是的,我的代码还没有完成,所以我目前不太担心缩进。我删除了最后的 elif 行以避免混淆。
  • 嗯...你不是在迭代字符。您使用readlines 来初始化数据;你的循环是在线条上,而不是字符上。

标签: python text document counting non-alphanumeric


【解决方案1】:

试试

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)

【讨论】:

  • 不知道isalnum() 在标准库中,这太棒了!这绝对是最简单的解决方案。
  • 我更新了我的代码,但现在它说 non_alpha_num 是未定义的。
  • @Jake 你在进入循环之前把它初始化为 0 了吗?
  • @Jake Do non_alpha_num=0 在循环之前
  • 我试过了,但我得到了奇怪的输出。我再次更新了我的代码。
猜你喜欢
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2011-02-28
  • 2020-10-08
相关资源
最近更新 更多