python

2013-05-20 34 views
1

我有一個文本文件,其中有成千上萬行類似這樣的格式(a,b,c,d,e)(這裏,a是6被編號,b是3個字母代碼,c是日期,d是浮點數,e是-1,0或1)我想用這種格式(b,c,d)對它進行重新設置。 例如(345678,'ABC','2010-01-01',0.123,'-1')=>('ABC','2010-01-01',0.123)python

我只是不知道從哪裏開始?在python中如果我將行分配給一個變量,那麼必須做什麼?分裂還是別的什麼?

我有Perl的一些知識太多,所以在任何這些twlo LANGS任何幫助將不勝感激 - ))

text = open('text.txt', 'w') 

for line in text: 
    # 
    # 
    # 
+0

爲什麼包含'perl'標籤時主題說python? –

回答

2

斯普利特,\s()焦炭類線,其值爲從2,3,4的位置,並把()他們周圍。

perl -F'[,\s\(\)]+' -ape '$_ = join ", ", @F[2,3,4]; $_ = "($_)"' text.txt 
0

你需要沿着這些路線的東西: -

for line in text: 
    line = line.strip('()') 
    fields = line.split(',') 
    print "(%s,%s,%s)" % (fields[1], fields[2], fields[3]) 

如果你使用的是unix系統,你可能需要考慮sed或awk。

3

像這樣?

import ast 
with open("in.txt") as infile, open("out.txt", "w") as outfile: 
    for line in infile: 
     contents = ast.literal_eval(line) 
     outfile.write(str(contents[1:4])) 
+0

Damnit。只是打敗了我 – TerryA

0
for line in text 
    s = line.split(',') 
    print("({0},{1},{2})".format(s[1], s[2], s[3]))