计算大写字母,小写字母和其他字符

时间:2017-03-03 02:40:01

标签: jes

编写一个接受句子作为控制台输入的程序,并计算大写字母,小写字母和其他字符的数量。

假设为程序提供了以下输入: Hello World;!#

1 个答案:

答案 0 :(得分:1)

由于这个问题听起来像编程任务,我写的这是一个更加罗嗦的方式。这是标准的Python 3,而不是Jes。

#! /usr/bin/env python3

import sys

upper_case_chars = 0
lower_case_chars = 0
total_chars = 0
found_eof = False

# Read character after character from stdin, processing it in turn
# Stop if an error is encountered, or End-Of-File happens.
while (not found_eof):
    try:
        letter = str(sys.stdin.read(1))
    except:
        # handle any I/O error somewhat cleanly
        break

    if (letter != ''):
        total_chars += 1
        if (letter >= 'A' and letter <= 'Z'):
            upper_case_chars += 1
        elif (letter >= 'a' and letter <= 'z'):
            lower_case_chars += 1
    else:
        found_eof = True

# write the results to the console
print("Upper-case Letters: %3u" % (upper_case_chars))
print("Lower-case Letters: %3u" % (lower_case_chars))
print("Other Letters:      %3u" % (total_chars - (upper_case_chars + lower_case_chars)))

请注意,您应该修改代码以自行处理行尾字符。目前,他们被视为&#34;其他&#34;。我也没有处理二进制输入,可能 str()会失败。