Python:如何使用 .split 命令计算句子中的平均字长?

新手上路,请多包涵

这里是 python 的新手。我正在尝试编写一个程序来计算句子中的平均字长,我必须使用 .split 命令来完成。顺便说一句,我使用的是 python 3.2

这是我到目前为止所写的

sentence = input("Please enter a sentence: ")
print(sentence.split())

到目前为止,我让用户输入一个句子,它成功地拆分了他们输入的每个单词,例如:嗨,我的名字是 Bob,它将它拆分为 [‘hi’, ‘my’, ‘name’, ‘is’, ‘鲍勃]

但现在我迷路了,我不知道如何让它计算每个单词并找到句子的平均长度。

原文由 Average kid 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 803
2 个回答

在 Python 3(您似乎正在使用)中:

 >>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> average = sum(len(word) for word in words) / len(words)
>>> average
2.6

原文由 Tim Pietzcker 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可能想要过滤掉标点符号和零长度单词。

 >>> sentence = input("Please enter a sentence: ")

过滤掉不重要的标点符号。如果需要,您可以在标点符号字符串中添加更多内容:

 >>> filtered = ''.join(filter(lambda x: x not in '".,;!-', sentence))

拆分成单词,并删除长度为零的单词:

 >>> words = [word for word in filtered.split() if word]

并计算:

 >>> avg = sum(map(len, words))/len(words)
>>> print(avg)
3.923076923076923

原文由 Lennart Regebro 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题