在本文中,我们将学习下面给出的问题陈述的解决方案。
问题陈述 -给我们一个字符串,我们需要计算该字符串中的单词数
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
此处的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
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
所有变量均在本地范围内声明,其引用如上图所示。
在本文中,我们学习了如何计算句子中的单词数。