如何计算 python 中字符串中的单词数
How to count words in a string in python
我希望能够输入一个词,然后 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 来计算段落中的单词直到时间到了用户输入的单词并打印该数字
您可以使用 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
这是一个非常简单的实现;如果有重复的单词等,这将不起作用。
我希望能够输入一个词,然后 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 来计算段落中的单词直到时间到了用户输入的单词并打印该数字
您可以使用 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
这是一个非常简单的实现;如果有重复的单词等,这将不起作用。