简体   繁体   English

计算字符串中的单词数

[英]Count the number of words in a string

what I'm doing right now is counting the number of spaces, then add 1 我现在正在做的是计算空格数,然后加1
but what if the user enters something like "heres a big space______amazing right?" 但是,如果用户输入诸如"heres a big space______amazing right?"类的东西"heres a big space______amazing right?"
the program would count all those 6 spaces and say, there are 10 words when actually it is 6 该程序将计算所有这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"

Use str.split() to split a line on whitespace, then use the length of the result: 使用str.split()str.split()分割一行,然后使用结果的长度:

len(phrase.split())

str.split() with no arguments, or None as the first argument, will split on arbitrary width whitespace; 没有参数或第一个参数为None str.split()将在任意宽度的 str.split()分割; no matter how many spaces or tabs or newlines are used between words, it'll split to produce just a list of words (where a word is anything that is not whitespace): 不管有多少个空格或制表符,换行符词与词之间的使用,它会分解产生只是一个单词的列表(其中一个词是什么,是不是空格):

>>> 'Hello world!  This\tis\t         awesome!'.split()
['Hello', 'world!', 'This', 'is', 'awesome!']
>>> len('Hello world!  This\tis\t         awesome!'.split())
5
>>> import re
>>> s = "test  test1    test2    abc"
>>> re.findall("\w+", s)
['test', 'test1', 'test2', 'abc']
>>> ret = re.findall("\w+", s)
>>> len(ret)
4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM