![](/img/trans.png)
[英]Python / Dictionary / List / Mongo insert issues - beginner
[英]Python beginner issues - dictionary
我一直在嘗試產生一個帶有輸出的程序:
Enter line: which witch
Enter line: is which
Enter line:
is 1
which 2
witch 1
我希望它的工作方式是讓您輸入幾行,當什么都沒有提交時,它將計算每行的數量。
目前,我無法計算一個句子中的每一行,而只能計算整個句子。 我的代碼:
dic = {}
while True:
line = input('Enter Line: ')
line = line.lower()
if not line:
break
dic.setdefault(line, 0)
dic[line] += 1
for line, n in sorted(dic.items()):
print(line, n)
產生輸出:
Enter line: which witch
Enter line: is which
Enter line:
which witch 1
is which 1
而不是第一個
任何幫助,將不勝感激。 謝謝
該代碼將每一行用作字典鍵,而不是單詞。 使用str.split
分割行並迭代單詞。
dic = {}
while True:
line = input('Enter Line: ')
line = line.lower()
if not line:
break
for word in line.split(): # <-----
dic.setdefault(word, 0) # <-----
dic[word] += 1 # <-----
for line, n in sorted(dic.items()):
print(line, n)
順便說一句,考慮將collections.Counter
用於此類任務(對事件進行計數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.