0

我正在使用如何像计算机科学家一样思考互动版学习 Python,其中一个练习具有以下要求:

“为程序中的变量分配一个三引号字符串,其中包含您最喜欢的文本段落——可能是一首诗、一段演讲、烤蛋糕的说明、一些鼓舞人心的诗句等。

编写一个函数来计算文本中字母字符(a 到 z 或 A 到 Z)的数量,然后跟踪字母“e”有多少个。您的函数应该像这样打印文本分析:

您的文本包含 243 个字母字符,其中 109 个(44.8%)是 'e'。”

我写的代码(对我来说)似乎完全按照我的要求做,但是当我检查他们的解决方案来测试我的代码时,我得到了不同的结果。

我的代码:

text = ''' "If the automobile had followed the same development cycle as the computer, a
Rolls-Royce would today cost $100, get a million miles per gallon, and explode
once a year, killing everyone inside."
-Robert Cringely'''

lowercase_text = text.lower()

def charCounter(some_text):
    e_counter = 0
    char_counter = 0

    for char in lowercase_text:    
        if char == 'e':
            e_counter = e_counter + 1
        else:
            char_counter = char_counter + 1

    return ("Your text contains " + str(char_counter) +  " alphabetic characters, of which " + str(e_counter) + " (" + str((e_counter / char_counter) * 100) + "%)" +  "are 'e'.")

我的代码输出:

Your text contains 188 alphabetic characters, of which 25 (13.297872340425531%)are 'e'.

作者提供的解决方案代码:

def count(p):
    lows="abcdefghijklmnopqrstuvwxyz"
    ups="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    numberOfe = 0
    totalChars = 0
    for achar in p:
        if achar in lows or achar in ups:
            totalChars = totalChars + 1
            if achar == 'e':
                numberOfe = numberOfe + 1


    percent_with_e = (numberOfe/totalChars) * 100
    print("Your text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.")


p = '''"If the automobile had followed the same development cycle as the computer, a
Rolls-Royce would today cost $100, get a million miles per gallon, and explode
once a year, killing everyone inside."
-Robert Cringely'''

count(p)

作者解决方案输出的代码:

Your text contains 166 alphabetic characters of which 25 ( 15.060240963855422 %) are 'e'.

有人可以解释我做错了什么吗?我不明白为什么结果会有这种差异。

4

3 回答 3

4

您的解决方案不检查字符是否确实是字母数字并且也计算空格。此外,“e”不计入总字符数。

问题出在你的 for 循环中:

for char in lowercase_text:    
    if char == 'e':
        e_counter = e_counter + 1
    else:
        char_counter = char_counter + 1

它应该如下所示:

for char in lowercase_text:    
    # Check if we have an alphanumeric string and continue the loop if not
    if not char.isalpha():
        continue
    # Increment the total character counter
    char_counter += 1
    # Additionaly, increment the 'e' counter if we have an 'e'
    if char == 'e':
        e_counter += 1
于 2013-09-27T11:31:20.917 回答
0

您在计数中包含标点符号、数字和空格,您不应该这样做。

于 2013-09-27T11:28:23.977 回答
0

我没有解决这个问题的方法,因为它已经解决了(请不要反对),我只是想提出一种更 Pythonic 的方法来解决这个问题(也不需要赞成):

import string

text = ''' "If the automobile had followed the same development cycle as the computer, a
Rolls-Royce would today cost $100, get a million miles per gallon, and explode
once a year, killing everyone inside."
-Robert Cringely'''

def check_character(text, character):
    text = text.lower()
    count_sum = len(list(c for c in text if c in string.ascii_lowercase))
    count_char = len(list(c for c in text if c == character))
    return count_sum, count_char, 100 * count_char / float(count_sum)

char = 'e'
result = check_character(text, char) + (char,)

print("Your text contains {} alphabetic characters of which {} ({:.2f}%) are '{}'.".format(*result))
于 2013-09-27T11:59:06.417 回答