2014-02-14 36 views
0

我不是在說一個特定的單詞或字母有多少次,而是一個字符串中有多少單詞。ICount字符串中有多少個單詞

這裏是到目前爲止的代碼:

list = [] 
x = raw_input("Text: ") 
x.split() 

abc = x.split(" ") 
list.append(abc) 
print list.count(",")#here i tried to count how many time "," shows up 
#and have it where if it says 1 time then their is two, three times then 
#there is 4 words, but it does not work and Would not be accurate if i typed "hello, again" 

我怎麼能算多少字在字符串中?謝謝

+0

會不會'x.count(」「)+ 1'幫助?或'len(x.split())'選項卡和換行符。 – WKPlus

+0

爲什麼不只是'len(abc)'? – mhlester

+0

'list'是a)一個不好的名字(它影響了一個內建的名字,它不是描述性的),b)對你沒有任何幫助。 –

回答

0

也許這些方式可以幫助:

x = raw_input("Text: ") 
print len(x.split()) 

或者:

import re 
x = raw_input("Text: ") 
r=re.compile(r"\b") 
print len(re.findall(r,x))/2 
0

確定構成一個詞實際上是一個相當棘手的問題,但如果你只是指那些有空間之間,那並不難。

list = [] 
x = raw_input("Text: ") 
x.split() 

abc = x.split(" ") # print out or otherwise view `abc` -- 
list.append(abc) # I'm not sure what you want to accomplish here -- this 
       # puts your list `abc` in your list `list`. 
print list.count(",") # I'm not sure why you think `list` would have "," in it 
         # list has only one thing in it -- another list (abc) 

也許這將有助於看一個例子。

>>> list = [] # DON'T CALL IT 'list', give it a different name 
>>> x = raw_input("Text: ") 
Text: Now is the time for all good men to come to the aid of their country. 
>>> x 
'Now is the time for all good men to come to the aid of their country.' 
>>> abc = x.split() 
>>> abc 
['Now', 'is', 'the', 'time', 'for', 'all', 'good', 'men', 'to', 'come', 'to', 'the', 'aid', 'of', 'their', 'country.'] 
>>> list.append(abc) 
>>> list 
[['Now', 'is', 'the', 'time', 'for', 'all', 'good', 'men', 'to', 'come', 'to', 'the', 'aid', 'of', 'their', 'country.']] 
>>> list[0] 
['Now', 'is', 'the', 'time', 'for', 'all', 'good', 'men', 'to', 'come', 'to', 'the', 'aid', 'of', 'their', 'country.'] 
>>> list[0][0] 
'Now' 
相關問題