Python程式中句子單詞計數


在這篇文章中,我們將學習如何解決下面給出的問題。

問題陳述 - 給定一個字串,我們需要計算字串中單詞的數量。

方法一 - 使用split()函式

split()函式使用空格作為分隔符,將字串分割成一個列表可迭代物件。如果使用split()函式時沒有指定分隔符,則預設為空格。

示例

即時演示

test_string = "Tutorials point 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 : Tutorials point is a learning platform
The number of words in string are : 6

方法二 - 使用正則表示式模組

這裡使用findall()函式來計算正則表示式模組中給定句子中的單詞數量。

示例

即時演示

import re
test_string = "Tutorials point 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))

輸出

原文為:Tutorials point is a learning platform 字串中的單詞數量為:6

方法三 - 使用sum()+ strip()+ split()函式

在這裡,我們首先檢查給定句子中的所有單詞,並使用sum()函式將它們加起來。

示例

即時演示

import string
test_string = "Tutorials point 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 : Tutorials point is a learning platform
The number of words in string are : 6

所有變數都在區域性作用域中宣告(另請閱讀:區域性和全域性變數),它們在上面的圖中可見。

結論

在這篇文章中,我們學習瞭如何計算句子中單詞的數量。

更新於:2023年8月25日

35K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告