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

2024-04-27 03:50:47 发布

您现在位置: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函数来计算段落中的单词,直到时间到了用户输入的单词为止,然后打印这个数字


Tags: theto用户程序readinputif单词
1条回答
网友
1楼 · 发布于 2024-04-27 03:50:47

可以使用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

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

相关问题 更多 >