首页 > 解决方案 > 如何让我的代码区分单词和单数字符?(Python)

问题描述

(Python) 我的任务是创建一个程序来收集 input() 并将其放入字典中。对于文本的每个单词,它都会计算它在它之前出现的次数。我的代码:

text = input()

words = {}

for word in text:
    if word not in words:
        words[word] = 0
        print(words[word])

    elif word in words:
        words[word] = words[word] + 1
        print(words[word])

一个示例输入可能是:

one two one two three two four three

正确的输出应该是:

0
0
1
1
0
2
0
1

但是,我的代码会计算每个字符的出现次数,而不是每个单词都会使输出变得太长。如何区分单词和字符?

标签: pythondictionaryinput

解决方案


那是因为text是一个字符串,并且迭代一个字符串会迭代字符。您可以使用for word in text.split(),这会将字符串拆分为列表。默认情况下,它会对空格进行拆分,因此它会在此处将其拆分为单词列表。


推荐阅读