我該如何計算句子中的單詞?我正在使用Python。如何計算一個句子中的單詞數量?
例如,我可能有串:
string = "I am having a very nice [email protected]$ day. "
這將是7個字。在每個單詞之後/之前以及涉及數字或符號時,我遇到了隨機空間量的問題。
我該如何計算句子中的單詞?我正在使用Python。如何計算一個句子中的單詞數量?
例如,我可能有串:
string = "I am having a very nice [email protected]$ day. "
這將是7個字。在每個單詞之後/之前以及涉及數字或符號時,我遇到了隨機空間量的問題。
str.split()
沒有任何參數分割上的空白字符運行:
>>> s = 'I am having a very nice day.'
>>>
>>> len(s.split())
7
從鏈接的文檔:未指定
如果月或
None
,一個不同的分割算法被應用於:連續空格的運行被認爲是一個單獨的分隔符,並且如果該字符串具有前導空格或尾隨空格,則結果將在開始或結束處不包含空字符串。
這樣做的一個(非常小的)缺點是您可以將標點符號組計爲單詞。例如,在''我有一個非常愉快的一天 - 或者至少我是','你會'''算作一個字。我猜,'isalnum'可能會有所幫助,這取決於OP對「單詞」的定義。 – DSM
這似乎比正則表達式更快 –
您可以使用regex.findall()
:
import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)
確定這裏是我的版本做這個的。我注意到你希望你的輸出是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!
這是一個簡單的字計數器使用正則表達式。該腳本包含一個循環,您可以在完成時終止它。
#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")
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
輸出是11.再次檢查。 –
謝謝我,我糾正了。 –
,以適應數字,你可以改變正則表達式。 '\ w'匹配'[a-zA-Z0-9]'現在,你需要定義你的用例。 「我很好2」會發生什麼?會是2個單詞還是3個? – karthikr