如何在Python中计算字符串中的单词数

问题描述 投票:0回答:2

我希望能够输入一个单词,然后让 python 计算上一段中直到该单词的单词数。

这是一个程序,可以帮助您了解一分钟内可以阅读多少单词。打印一个段落并设置一分钟的计时器。当一分钟结束时,用户输入他们在段落中到达的单词,程序必须告诉您到目前为止您读了多少单词。

print ('write start to begin the program')
x = ('')

if x == (''):
    x = input()

if x == 'start':
    import threading 
    def yyy(): 
        print("time is up")
        print('write the last word you read')
        word = input()
        #MISSING CODE

    timer = threading.Timer(10.0, yyy) 
    timer.start()
    print ('paragraph to read')

这被缩短了,但我需要一个Python函数来计算段落中的单词,直到时间到了用户输入的单词为止,并打印该数字

python count cpu-word paragraph
2个回答
1
投票

您可以使用

split()
将段落字符串拆分为单词列表:

#paragraph_text = "One two three four"
words = paragraph_text.split(' ')
#words = ["One", "two", "three", "four"]

然后您可以循环浏览此列表,将其与用户输入的单词进行比较:

for counter, candidate in enumerate(words):
    if candidate == word:
        print("You have read %s words!" % (counter + 1))
        #Other actions
        break

这是一个非常简单的实现;如果有重复的单词等,这将不起作用。


0
投票

实际上可以使用

str.split()
。但请远离任何参数,因为默认情况下它会处理所有空格字符,包括
\n\r\t\f
。如果按照之前的答案给出
' '
表明您可能会得到错误的结果。另外,正如
split
的帮助中所述,自然文本的写入方式是使用正则表达式。

split(自我,/,sep=无,maxsplit=-1) 返回字符串中子字符串的列表,使用 sep 作为分隔符字符串。

  sep
    The separator used to split the string.

    When set to None (the default value), will split on any whitespace
    character (including \n \r \t \f and spaces) and will discard
    empty strings from the result.
  maxsplit
    Maximum number of splits (starting from the left).
    -1 (the default value) means no limit.

Note, str.split() is mainly useful for data that has been intentionally
delimited.  With natural text that includes punctuation, consider using
the regular expression module.
© www.soinside.com 2019 - 2024. All rights reserved.