简体   繁体   English

计算句子中用空格隔开的所有单词

[英]Count all words in a sentence separated by spaces

in Python I want an user to type a sentence using the Input argument. 在Python中,我希望用户使用Input参数键入一个句子。

zin = input("Typ een zinnetje: ")

In a function I want to count all words (everything separated by spaces.) how do I do this? 在一个函数中,我想计算所有单词(所有单词之间用空格隔开。)我该怎么做?

this is what I have so far. 这是我到目前为止所拥有的。

zin = input("Typ een zinnetje: ")
def gemiddelde():
    aantal = zin.count(zin)
    return aantal

print (gemiddelde())

This prints 1 no matter what. 无论如何,都会打印1。

split will break string by space and len will return length: split将按空格split字符串, len将返回长度:

zin = input("Typ een zinnetje: ")
def gemiddelde():
    aantal = len(zin.split())
    return aantal

print (gemiddelde())

you need to split sentence by space and then use len 您需要按空格分隔句子,然后使用len

zin = raw_input("Typ een zinnetje: ")
def gemiddelde():
    aantal = len(zin.split(' '))
    return aantal

print (gemiddelde())
zin = input("Typ een zinnetje: ")
def gemiddelde():
        aantal = zin.split(" ")
        return aantal.__len__()

print (gemiddelde())

Further to the answers before me, split will split the string on every occurrence of a space meaning that it may read more words if there are things like double spaces or leading/trailing spaces. 除了我之前的答案之外,split还会在每次出现空格时将字符串分割开,这意味着如果存在双精度空格或前导/后缀空格之类的东西,它可能会读取更多单词。 It may be worth doing some quick checks to make sure what you get is actually the number of words. 可能需要进行一些快速检查以确保您得到的实际上是单词数。

zin = input("Typ een zinnetje: ")

def gemiddelde():
    aantal = zin.split(" ")
    num = sum(len(x) > 0 for x in aantal)
    return num

print (gemiddelde())

In a single line, 在一行中,

def count_words(s):
    return len(s.split())

The split() function will split the string s into list of words , where the delimiter for the split is whitespace . split()函数会将string s拆分list of words ,其中分隔符为whitespace The len() will return the number of elements that were obtained when the string was split. len()将返回拆分字符串时获得的元素数。

zin = input("Typ een zinnetje: ")

def gemiddelde(s):
    return len(s.split(' '))

print (gemiddelde(zin))

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

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