2013-10-16 120 views
35

我該如何計算句子中的單詞?我正在使用Python。如何計算一個句子中的單詞數量?

例如,我可能有串:

string = "I  am having a very nice [email protected]$  day. " 

這將是7個字。在每個單詞之後/之前以及涉及數字或符號時,我遇到了隨機空間量的問題。

+2

,以適應數字,你可以改變正則表達式。 '\ w'匹配'[a-zA-Z0-9]'現在,你需要定義你的用例。 「我很好2」會發生什麼?會是2個單詞還是3個? – karthikr

回答

56

str.split()沒有任何參數分割上的空白字符運行:

>>> s = 'I am having a very nice day.' 
>>> 
>>> len(s.split()) 
7 

從鏈接的文檔:未指定

如果None,一個不同的分割算法被應用於:連續空格的運行被認爲是一個單獨的分隔符,並且如果該字符串具有前導空格或尾隨空格,則結果將在開始或結束處不包含空字符串。

+7

這樣做的一個(非常小的)缺點是您可以將標點符號組計爲單詞。例如,在''我有一個非常愉快的一天 - 或者至少我是','你會'''算作一個字。我猜,'isalnum'可能會有所幫助,這取決於OP對「單詞」的定義。 – DSM

+0

這似乎比正則表達式更快 –

33

您可以使用regex.findall()

import re 
line = " I am having a very nice day." 
count = len(re.findall(r'\w+', line)) 
print (count) 
+0

嗯,如果可以的話,我通常會避免使用正則表達式,但這似乎是一個相當不錯的用例。 –

+4

+1使用're',它確實比'[i for string.split()if i.isalnum()]更好' – JadedTuna

+0

我寧願依靠計算'\ S +'來處理像decimal數字在'「它快了2.5倍」' – Emadpres

1

確定這裏是我的版本做這個的。我注意到你希望你的輸出是7,這意味着你不想計算特殊字符和數字。因此,這裏是正則表達式:

re.findall("[a-zA-Z_]+", string) 

[a-zA-Z_]意味着它會匹配任何字符 beetwen a-z(小寫),A-Z(大寫)。


關於空格。如果你想刪除所有額外的空間,只是做:

string = string.rstrip().lstrip() # Remove all extra spaces at the start and at the end of the string 
while " " in string: # While there are 2 spaces beetwen words in our string... 
    string = string.replace(" ", " ") # ... replace them by one space! 
2

這是一個簡單的字計數器使用正則表達式。該腳本包含一個循環,您可以在完成時終止它。

#word counter using regex 
import re 
while True: 
    string =raw_input("Enter the string: ") 
    count = len(re.findall("[a-zA-Z_]+", string)) 
    if line == "Done": #command to terminate the loop 
     break 
    print (count) 
print ("Terminated") 
-1
def wordCount(mystring): 
     tempcount = 0 
     count = 1 

     try: 
      for character in mystring: 
       if character == " ": 
        tempcount +=1 
        if tempcount ==1: 
         count +=1 

        else: 
         tempcount +=1 
       else: 
        tempcount=0 

      return count 

     except Exception: 
      error = "Not a string" 
      return error 

    mystring = "I am having a very nice [email protected]$  day."   

    print(wordCount(mystring)) 

輸出爲8

+0

輸出是11.再次檢查。 –

+0

謝謝我,我糾正了。 –

相關問題