我正在使用如何思考计算机科学家互动版学习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'.
有人可以解释一下我做错了什么吗?我不明白为什么结果会有这种差异。
答案 0 :(得分: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
答案 1 :(得分:0)
您在计数中包含标点符号,数字和空格,您不应该这样做。
答案 2 :(得分:0)
我已经无法解决问题,因为它已经解决了(请不要下载),我只是想提出一个更加pythonic的方法来解决这个问题(也不需要upvotes):
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))