溫馨提示×

python如何統計字符串中單詞個數

小億
298
2023-11-07 16:27:38
欄目: 編程語言

可以使用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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女