【问题标题】:automatically generate document title from string list with Python使用 Python 从字符串列表自动生成文档标题
【发布时间】:2012-12-25 08:50:19
【问题描述】:

我正在尝试根据频道组织新闻,即我需要使用list_a(如下)中的元素来命名我的txt文件,然后将同一频道的相应字符串写入同一文档。 这些 txt 文件可以写入我当前的文件夹,这没有什么麻烦

我目前关心的是如何高效地编写它。由于我不知道要在文档中写入多少字符串,因此当前文档需要保留,直到字符串用尽并启动新文档。

以下是一个例子:

输入: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

【问题讨论】:

  • 那么,列表总是这样排列的吗? [chanX, chanY, chanZ] 和 [new_from_chan_x, new_from_chan_y, new_from_chan_z]?,如果是这样,你可以用 zip() 来完成

标签: python list title


【解决方案1】:

您可以在此处使用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')

【讨论】:

    【解决方案2】:

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

    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))
    

    【讨论】:

      【解决方案3】:

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

      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")
      

      【讨论】:

      • sort() 自 Python 2.2 以来保证稳定,即具有相同标题的项目应保持顺序。
      • @AshwiniChaudhary:你是对的。我忘记向 sorted() 添加键以保留顺序。固定。
      猜你喜欢
      • 2015-06-22
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2013-03-19
      • 2018-09-27
      • 2011-07-08
      • 2021-09-11
      相关资源
      最近更新 更多