python - 如何让我的代码区分单词和单数字符?(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
但是,我的代码会计算每个字符的出现次数,而不是每个单词都会使输出变得太长。如何区分单词和字符?
解决方案
那是因为text
是一个字符串,并且迭代一个字符串会迭代字符。您可以使用for word in text.split()
,这会将字符串拆分为列表。默认情况下,它会对空格进行拆分,因此它会在此处将其拆分为单词列表。
推荐阅读
- vhdl - 图像 ROM 显示 VGA
- r - 将字符串列表或向量拆分为R中的虚拟列
- regex - 如何显示不包含字符或数字的记录?
- json - 当我不知道字典的键时,如何从 JSON 解码字典?
- r - 如何在sf R包中按组测量空间点之间的距离
- r - 如何计算活动的平均小时数?
- regex - 使用 seq 和 regex 选择新行并将其添加到 xml 文件
- python - 通过机器人框架在 Excel 表中写入数据/更改不起作用并获取 IndexError:列表索引超出范围
- python - SQLAlchemy 次要关系不使用 JOIN
- java - OCP(开放封闭原则)与 IoC(控制反转)有什么关系?