python如何统计字符串中单词个数

1303
2023/10/19 16:27:38
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

可以使用split()方法将字符串分割成单词,并使用len()函数统计单词的个数。例如:

string = "Hello, how are you?"
words = string.split()
word_count = len(words)
print(word_count)

输出结果为:

4

另外,如果需要统计字符串中特定单词的个数,可以使用count()方法。例如:

string = "Hello, how are you?"
word = "you"
word_count = string.count(word)
print(word_count)

输出结果为:

1

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 怎么使用Python进行图像的HDR处理