2013-01-10 49 views
1

我试图根据通道组织新闻,即我需要使用list_a(下面)中的元素来命名我的txt文件,然后将相同频道的相应字符串写入同一文件。 这些txt文件可以写入我目前的折叠,没有这方面的麻烦用Python自动生成字符串列表的文档标题

我目前的担心是如何有效地编写它。因为我不知道有多少串将被写入文件做,当前文档需要坚持到字符串耗尽,新的文档踢

下面是一个例子:

输入:2串列表:

list_a=['abc','abc','fox','abc',....] 

list_b=['campus shooting', 'Congress sucks', 'debt ceiling','1% rich', ...] 

输出: 2文件与标题 '的abc.txt' 和 'fox.txt' 分别

在文档的abc.txt

campus shooting 

congress sucks 

在文件fox.txt

debt ceiling 
+0

所以,列表总是这样的顺序? [chanX,chanY,chanZ]和[new_from_chan_x,new_from_chan_y,new_from_chan_z] ?,如果是这样,你可以使用zip() – israelord

回答

2

,你可以在这里使用zip()和追加模式打开文件('a'):

In [44]: list_a=['abc','abc','fox','abc'] 
In [45]: list_b=['campus shooting', 'Congress sucks', 'debt ceiling','1% rich'] 

In [46]: for x,y in zip(list_a,list_b): 
    ....:  with open(x+".txt" , "a") as f: 
    ....:   f.write(y+'\n') 
1

,只有一次打开文件的另一种方法:

from collections import defaultdict 

list_a = ['abc', 'abc', 'fox', 'abc'] 
list_b = ['campus shooting', 'Congress sucks', 'debt ceiling','1% rich'] 

results = defaultdict(list) 

for title, text in zip(list_a, list_b): 
    results[title].append(text) 

for title, result in results.iteritems(): 
    with open("%s.txt" % title , "w") as f: 
     f.write('\n'.join(result)) 
1

打开每个项目的文件可能会很昂贵(不要猜测,比较性能与此版本,避免它):

from itertools import groupby 
from operator import itemgetter 

L = sorted(zip(list_a, list_b), key=itemgetter(0)) # sorted (a, b) pairs 
for name, group in groupby(L, key=itemgetter(0)): 
    with open(name + ".txt", "w") as file: 
     for a, b in group: 
      file.write(b + "\n") 
+1

+1这样做很好,但它会改变内容的顺序。 –

+0

自Python 2.2以来,'sort()'保证是稳定的,即具有相同标题的项目应该保持顺序。 – jfs

+0

@AshwiniChaudhary:你说得对。我忘了将keys添加到sorted()以保持顺序。固定。 – jfs