在这个练习中苦苦挣扎,必须使用字典并计算每个单词在多个用户输入中出现的次数。它以一种方式工作,但不会从每行用户输入中雾化每个单词。因此,不是将“快乐日”的输入计算为1 x快乐和1 x天,而是给我1 x快乐的日子。我已经尝试了split()和lower(),但这会将输入转换为列表,我正在努力将该列表倒入字典中。
正如您可能已经猜到的那样,我是一个新手,所以非常感谢所有帮助!
occurrences = {}
while True:
word = input('Enter line: ')
word = word.lower() #this is also where I have tried a split()
if word =='':
break
occurrences[word]=occurrences.get(word,0)+1
for word in (occurrences):
print(word, occurrences[word])
修改
欢呼回应。这最终成为最终的解决方案。他们并不担心案件,并希望最终结果排序()。
occurrences = {}
while True:
words = input('Enter line: ')
if words =='':
break
for word in words.split():
occurrences[word]=occurrences.get(word,0)+1
for word in sorted(occurrences):
print(word, occurrences[word])
答案 0 :(得分:0)
你所拥有的几乎就在那里,你只想在将它们添加到词典时循环翻译
occurrences = {}
while True:
words = input('Enter line: ')
words = words.lower() #this is also where I have tried a split()
if words =='':
break
for word in words.split():
occurrences[word]=occurrences.get(word,0)+1
for word in (occurrences):
print(word, occurrences[word])
答案 1 :(得分:0)
此行未执行:occurrence [word] = occurrence .get(字,0)+1
因为如果它进入if,它会进入中断并且永远不会执行该行。为了使它在if之外不要缩进它。
一般来说,发布的代码的缩进是混乱的,我想在你的实际代码中并不是那样。
答案 2 :(得分:0)
您想要逐行统计数据还是想要整体统计数据?我猜测你想要逐行,但你也可以通过在以下代码中取消注释几行来轻松获得整体统计数据:
# occurrences = dict() # create a dictionary here if yuo want to have incremental overall stats
while True:
words = input('Enter line: ')
if words =='':
break
word_list = words.lower().split()
print word_list
occurrences = dict() # create a dict here if you want line by line stats
for word in word_list:
occurrences[word] = occurrences.get(word,0)+1
## use the lines bellow if you want line by line stats
for k,v in occurrences.items():
print k, " X ", v
## use the lines bellow if you want overall stats
# for k,v in occurrences.items():
# print k, " X ", v