def word_count (x: str) -> str:
characters = len(x)
word = len(x.split())
average = sum(len(x) for x in word)/len(word)
print('Characters: ' + str(char) + '\n' + 'Words: ' + str(word) + '\n' + 'Avg word length: ' + str(avg) + '\n')
这段代码对于普通字符串正常工作,但是对于像这样的字符串:
'***The ?! quick brown cat: leaps over the sad boy.'
如何编辑代码,使“ ***”和“?!”等数字成为可能?不在代码中说明?以上句子的平均单词数应为3.888889,但我的代码给了我另一个数字。
试试这个:
import re
def avrg_count(x):
total_chars = len(re.sub(r'[^a-zA-Z0-9]', '', x))
num_words = len(re.sub(r'[^a-zA-Z0-9 ]', '', x).split())
print "Characters:{0}\nWords:{1}\nAverage word length: {2}".format(total_chars, num_words, total_chars/float(num_words))
phrase = '***The ?! quick brown cat: leaps over the sad boy.'
avrg_count(phrase)
输出:
Characters:34
Words:9
Average word length: 3.77777777778
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句