python - 查找字符串中的平均字长

标签 python string average

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,但我的代码给了我另一个数字。

最佳答案

字符串有一个 .translate() 方法,您可以使用它(如果您知道要删除的所有字符):

>>> "***foo ?! bar".translate(None, "*?!")
'foo  bar'

关于python - 查找字符串中的平均字长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33446997/

相关文章:

python - 溢出错误 : long int too large to convert to float in python

Windows PATH 到 bash 中的 posix 路径转换

java - 计算数组列表的平均值?

java - 如何找到该学生数组中所有学生的最高、最低和总平均数

python - 查找列表中项目的平均长度。 Python

python - 找不到 python_version 的本地包或工作下载链接(认为它存在)

python - 将一个字典合并到另一个仅具有公共(public)字段的字典中

python - 全局变量声明Python

php - 将国家字符转换为 PHP 中的拉丁字符

c++ - 'INT'- 'INT'在C++中表示什么?