【发布时间】:2020-11-23 17:31:22
【问题描述】:
输出与它的外观完全不同,我尝试修复了几次,但我需要帮助。
我的代码:
def main():
fruit = open("fruit.txt")
wordDict = {}
for line in fruit:
words = line.split(" ")
for word in words:
if len(word) > 0:
word = word.lower()
if word in wordDict.keys():
wordDict[word] += 1
print(word, "appears in line(s)", wordDict)
else:
wordDict[word] = 1
for key in sorted(wordDict):
print(" {0} : {1} ".format(key, wordDict[key]))
main()
输出应该如下所示:
apples appear in line(s) 1
orange appears in line(s) 1 6
grapes appears in line(s) 1 2 3 6
bananas appears in line(s) 1 6
watermelon appears in line(s) 1 4
peaches appears in line(s) 1 4
strawberries appears in line(s) 1 4
avocado appears in line(s) 2
cantaloupes appears in line(s) 2 5
apricots appears in line(s) 2 5
nectarines appears in line(s) 2
lemons appears in line(s) 3
limes appears in line(s) 3
CURRENT OUTPUT:
葡萄排成一行 西瓜出现在行中 桃子出现在行中 草莓 出现在行中 cantalopes 出现在行中 橙色出现在行中 葡萄出现在行中
: 1 苹果:1个 杏子:1 杏子 : 1 鳄梨:1 香蕉:1 香蕉 : 1 甜瓜:2 葡萄:3 葡萄 : 1 柠檬:1个 青柠 : 1 油桃:1 橙色:2 桃子:2个 草莓 : 2 西瓜:2个
``` FRUIT.TXT FILE
apples orange grapes bananas watermelon peaches strawberries
avocado cantalopes appricots nectarines grapes
grapes lemons limes
watermelon peaches strawberries
cantalopes appricots
orange grapes bananas
【问题讨论】:
-
你能附上
fruit.txt文件和你当前的输出吗? -
@asdasd 的fruit.txt 文件是苹果、橙子、葡萄、香蕉、西瓜桃、草莓、鳄梨、甜瓜、杏、油桃、葡萄、葡萄、柠檬、青柠、西瓜桃、草莓、甜瓜、杏、橙葡萄、香蕉
标签: python-3.x loops dictionary