好的,我刚刚用Python完成了我的第一个uni单元。对于大约3个小时前的期末考试,我编写了以下代码。我回家检查它是否有效,并且出现错误,但未给出任何有关修复方法的指导。错误提示:
<function wordcount at 0x7f857957df28> How many words, characters and spaces is this?
我希望别人能指出我的编码错误的代码在这里:
def wordcount(text):
wc = (0,0,0)
wc[1] = len(text)
spaces = 0
for x in range(text):
if text[x] == " ":
spaces += 1
wc[2] = spaces
wc[0] = spaces + 1
return wc
print(wordcount,"How many words, characters and spaces is this?")
答案 0 :(得分:0)
使用有效代码:
def wordcount(text):
Characters = sum(c.isalpha() for c in text)
spaces = sum(c.isspace() for c in text)
wordslist = text.split()
words = len(wordslist)
return (words,Characters,spaces)
print(wordcount("How many words, characters and spaces is this?"))
输出:
(8, 37, 7)
更正后的代码:
def wordcount(text):
wc = [0,0,0]
spaces = 0
for x in text:
if x == " ":
spaces += 1
wc[1] = len(text)-spaces
wc[2] = spaces
wc[0] = spaces + 1
return wc
print(wordcount("How many words, characters and spaces is this?"))