如何在python中安排数据

时间:2013-05-11 06:56:28

标签: python list

这是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%
....

我想摆脱结果中的大括号,撇号。

如何更改或重写以显示我想要的结果? 我会等你的帮忙!!

3 个答案:

答案 0 :(得分:2)

字典/ Counter s / set未订购。您必须先将其转换为list并对列表进行排序。

例如:

for key, val in sorted(counter.items()):  #or with key=lambda x:x[0]
    print "%s: %.1f%s" % (key, float(val) * 100 / len(counter), "%")

打印按键排序的值,同时:

for key, val in sorted(counter.items(), key=lambda x: (x[1], x[0])):
    print "%s: %.1f%s" % (key, float(val) * 100 / len(counter), "%")

按百分比对它们进行排序(如果两个项目具有相同的百分比,它们也按名称排序)。

<强>更新

关于您的解析问题,您必须strip以及{}

for line in f:
    if line.strip():
        for keyword in line.strip().strip('{}').split(','):
            keyword = keyword.strip("'")

如果您使用的是最近的python版本(如2.7和/或3),则可以改为使用ast.literal_eval

import ast
...
for line inf f:
    stripped = line.strip()
    if stripped:
        for keyword in ast.literal_eval(stripped):

但请注意,这将删除同一行上的重复键! (从你的例子来看,这似乎没问题......)

否则你可以这样做:

import ast
...
for line inf f:
    stripped = line.strip()
    if stripped:
        for keyword in ast.literal_eval('[' + stripped[1:-1] + ']'):

这将保留重复。

答案 1 :(得分:1)

使用sorted根据键/百分比对项目进行排序,因为dicts没有任何顺序。

from collections import Counter
counter = Counter()
import ast
keywords = []
with open("abc") as f:
    for line in f:
        #strip {} and split the line at ", " 
        line = line.strip("{}\n").split(", ")
        counter += Counter(x.strip('"') for x in line)

le = len(counter)    
for key,val in sorted(counter.items()):
    print "%s: %.1f%s" %(key, (val*1.0 / le)*100, '%')

print

for key,val in sorted(counter.items(), key = lambda x :(x[1],x[0]) ):
    print "%s: %.1f%s" %(key, (val*1.0 / le)*100, '%')

<强>输出:

'gold': 33.3%
'iron': 33.3%
'silver': 16.7%
'timber': 16.7%
'tungsten': 16.7%
'wood': 16.7%

'silver': 16.7%
'timber': 16.7%
'tungsten': 16.7%
'wood': 16.7%
'gold': 33.3%
'iron': 33.3%

答案 2 :(得分:1)

迷路{}的原因是你没有摆脱它们。
要做到这一点,只需将for循环更改为:

 for line in f:
     line = line.strip().strip('{}') # get rid of curly braces
     if line:
         ....

就印刷而言:

print "Sorted by Percentage"
for k,v in sorted(c.items(), key=lambda x: x[1]):
    print '{0}: {1:.2%}'.format(k, float(v)/len(c))
print 
print "Sorted by Name"
for k,v in  sorted(c.items(), key=lambda x :x[0]):
    print '{0}: {1:.2%}'.format(k, float(v)/len(c))