用于计算句子中单词数量的 Python 程序
pythonserver side programmingprogramming更新于 2025/7/13 17:48:17
在本文中,我们将了解解决给定问题陈述的解决方案和方法。
问题陈述
给定一个句子,我们需要计算句子中的单词数量
这里我们将讨论两种方法 −
方法 1 − 使用 split() 函数
示例
test_string = "Tutorials point "
res = len(test_string.split())
print ("字符串中的单词数为:" + str(res))
输出
字符串中的单词数为:2
方法 2 − 使用 strip() & isalpha() 函数
示例
import string
test_string = "Tutorials point "
res = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()])
print ("字符串中的单词数为:" + str(res))
输出
字符串中的单词数为:2
结论
在本文中,我们了解了计算句子中单词数的方法。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

