【问题标题】:calculating upper case letters ,lowercase letters, and other characters计算大写字母、小写字母和其他字符
【发布时间】:2017-03-03 11:19:49
【问题描述】:

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

假设以下输入提供给程序: 世界你好!#

【问题讨论】:

  • 用什么编程语言?啊,我猜也是“jes”(标签)或 Python。
  • 是的,使用 jes。谢谢。

标签: jes


【解决方案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)))

请注意,您应该修改代码以自己处理行尾字符。目前,它们被视为“其他”。我也忽略了二进制输入的处理,可能 str() 会失败。

【讨论】:

    猜你喜欢
    • 2020-01-04
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2014-10-03
    • 2019-08-08
    • 2013-02-04
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多