Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-10-28) 阅读数 7 #程序编程
文章标签 python

可以使用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
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门