这是这样的 data.txt 文件:
{'wood', 'iron', 'gold', 'silver'}
{'tungsten', 'iron', 'gold', 'timber'}
我想得到两种类型的结果,如下所示:
#FIRST TYPE: sorted by item
gold: 33.3%
iron: 33.3%
silver: 16.7%
timber: 16.7%
tungsten: 16.7%
#SECOND TYPE: sorted by percentage
silver: 16.7%
timber: 16.7%
tungsten: 16.7%
gold: 33.3%
iron: 33.3%
我为此结果显示我的代码
import collections
counter = collections.Counter()
keywords = []
with open("data.txt") as f:
for line in f:
if line.strip():
for keyword in line.split(','):
keywords.append(keyword.strip())
counter.update(keywords)
for key in counter:
print "%s: %.1f%s" %(key, (counter[key]*1.0 / len(counter))*100, '%')
但是我的结果是这样的
'silver'}: 16.7%
'iron': 33.3%
....
我想摆脱大括号,结果中的撇号。
如何更改或重写以显示我想要的结果?我会等你的帮助!!