ICount字符串中有多少个单词

时间:2014-02-14 02:17:02

标签: python string split word

我不是说它说了一个特定的单词或字母多少次,而是说一个字符串中有多少单词。

这是迄今为止的代码:

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"

如何计算字符串中有多少个单词?谢谢

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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'