在Python程序中计算句子中的单词

在本文中,我们将学习下面给出的问题陈述的解决方案。

问题陈述 -给我们一个字符串,我们需要计算该字符串中的单词数

方法1:使用split()方法

拆分功能将字符串分成一个以空格为定界符可迭代的列表。如果在split()未指定分隔符的情况下使用该函数,则将其分配为默认分隔符。

示例

test_string = "nhooo.com is a learning platform"
#original string
print ("The original string is : " + test_string)
# using split() function
res = len(test_string.split())
# total no of words
print ("The number of words in string are : " + str(res))

输出结果

The original string is : nhooo.com is a learning platform
The number of words in string are : 6

方法2:使用正则表达式模块

此处的findall()方法用于计算正则表达式模块中可用句子中的单词数。

示例

import re
test_string = "nhooo.com is a learning platform"
# original string
print ("The original string is : " + test_string)
# using regex (findall()) function
res = len(re.findall(r'\w+', test_string))
# total no of words
print ("The number of words in string are : " + str(res))

输出结果

原始字符串为:nhooo.com是一个学习平台字符串中的单词数为:6

方法3:使用sum()+ strip()+split()方法

在这里,我们首先检查给定句子中的所有单词,然后使用sum()函数将它们添加。

示例

import string
test_string = "nhooo.com is a learning platform"
# printing original string
print ("The original string is: " + test_string)
# using sum() + strip() + split() function
res = sum([i.strip(string.punctuation).isalpha() for i in
test_string.split()])
# no of words
print ("The number of words in string are : " + str(res))

输出结果

The original string is : nhooo.com is a learning platform
The number of words in string are : 6

所有变量均在本地范围内声明,其引用如上图所示。

结论

在本文中,我们学习了如何计算句子中的单词数。