计算字符串中的单词数

时间:2013-12-15 02:52:36

标签: python

我现在正在做的是计算空格数,然后加1 但是,如果用户输入"heres a big space______amazing right?"之类的内容,该怎么办? 程序将计算所有这6个空格并说,实际上它是6个单词时有10个单词

phrase = raw_input("Enter a phrase: ")
space_total = 0
for ch in phrase:
    if ch == " ":
        space_total += 1
words = space_total + 1
print "there are", words, "in the sentence"

2 个答案:

答案 0 :(得分:3)

使用str.split()在空格上拆分一行,然后使用结果的长度:

len(phrase.split())

str.split()没有参数,或None作为第一个参数,将在任意宽度空格上分割;无论在单词之间使用多少空格或制表符或换行符,它都会被拆分以生成只是一个单词列表(其中一个单词是 not 空白的任何单词) :

>>> 'Hello world!  This\tis\t         awesome!'.split()
['Hello', 'world!', 'This', 'is', 'awesome!']
>>> len('Hello world!  This\tis\t         awesome!'.split())
5

答案 1 :(得分:0)

>>> import re
>>> s = "test  test1    test2    abc"
>>> re.findall("\w+", s)
['test', 'test1', 'test2', 'abc']
>>> ret = re.findall("\w+", s)
>>> len(ret)
4