0

我有一个非常大的文本文件,其中包含以下数据行:

('#DownWithAssad', '1')
('#DownYoTLParty', '1')
('#Download', '8')
('#Download:', '2')
('#Downloads', '2')
('#DownstairsMixtape', '1')
('#DowntonAbbey', '12')
('#DowntonAbbey?', '1')
('#DowntonPBS', '23')
('#Downtonabbey', '1')
('#DowntownAbbey', '1')

这似乎是一个简单的问题,但我想将数据从最高到最低软化,所以它看起来像:

('#DowntonPBS', '23')
('#DowntonAbbey', '12')
('#Download', '8')
('#Download:', '2')
('#Downloads', '2')
('#DownstairsMixtape', '1')
('#DownWithAssad', '1')
('#DownYoTLParty', '1')
('#DowntonAbbey?', '1')
('#Downtonabbey', '1')
('#DowntownAbbey', '1')

我认为我可以消除括号 () 并将数据拆分为:

import sys

f = open(sys.argv[1])
for line in f:
    line = str(line)[1 : -1]
    for sect in line.split(','):
        print sect

但是我不确定从这里去哪里。

4

2 回答 2

4

您可以使用以下方法很容易地解析您的文本文件ast.literal_eval

with open(datafile) as f:
    file_sorted = sorted((ast.literal_eval(x) for x in f),
                         key=lambda z:(int(z[1]),z[0]),
                         reverse=True)

这个怎么运作:

(ast.literal_eval(x) for x in f)  #turn each line in your file into a tuple
key=lambda z:(int(z[1]),z[0])     #function to determine how things are sorted.  Basically
                                  #sort as tuples:  `( int(z[1]),z[0] )`
reverse=True                      #descending order instead of ascending
于 2012-11-27T04:02:48.747 回答
1

这与您正在尝试做的事情一致。请注意,以这种方式解析行非常脆弱(格式错误的行可能会破坏它)

from operator import itemgetter
import sys

result=[]
with open(sys.argv[1]) as f:
    for line in f:
        line = str(line.strip())[1: -1]
        sect1, sect2 = line.split(', ')
        sect1 = sect1[1: -1]
        sect2 = int(sect2[1: -1])
        result.append((sect1, sect2))

for line in sorted(result, key=itemgetter(1), reverse=True):
    print line

解析它的更好方法是使用literal_eval正则表达式。你知道字符串中出现引号字符或逗号时有什么特殊处理吗?

于 2012-11-27T04:20:56.193 回答