2013-06-29 68 views
0

我有5個班,以檢查文件是否屬於一類在python

即:

earn 

acq 

money 

fx 

crude 

我有大約20000的文件, 列表和我有一個文件「主題。 TXT」,即具有以下形式:

earn~6~7~4 

grain~9~1~2~12 

money~4~29 

等.. 其中數字對應於文件名,和詞對應的類。

我需要打印所有隻屬於我之前提到的類的文件, 「賺」, 「ACQ」, 「金錢」, 「FX」 和 「原油」

EX輸出: (賺-6.txt,7.txt,4.txt)

(ACQ-5 .TXT)

等..

我能打印在「topics.txt」所有可用的類,但我要打印僅5分特定的人。

import collections 
import sys 
sys.stdout=open('dicti1.txt','w') 
with open('topics.txt') as f: 
    d = collections.defaultdict(list) 
    for line in f: 
     value, *keys = line.strip().split('~') 
     for key in filter(None, keys): 
      d[key].append(value+".txt") 


for i in d.items(): 
    print(i)  
+0

你說的「下只,我以前提到的類」是什麼意思?不打印也有其他標籤的文件? –

+0

標籤下的文件:賺,acq,錢,外匯,原油 –

回答

0

除非我誤解了這個問題,否則您正在努力工作。另外我建議不要覆蓋sys.stdout

嘗試這樣:

interesting_types = ['earn', 'acq', 'money', 'fx', 'crude'] 
with open("in.txt") as in_file, open('out.txt', 'w') as out_file: 
    for l in in_file: 
     if l: 
      type, *filenames = l.strip().split("~") 
      if type in interesting_types: 
       out_file.write("({}-{})\n".format(type, ",".join(["{}.txt".format(x) for x in filenames]))) 
+0

它說:ValueError:太多的值解壓縮(預期2) –

+0

它在哪裏提高值錯誤,在分裂線(「〜」) ? –

+0

是的!..這裏是第5行 –

相關問題