python将列表写入文件

时间:2011-01-11 02:02:50

标签: python

我需要在python中写一个文件列表。我知道列表应该使用join方法转换为字符串,但由于我有一个元组,我感到困惑。我尝试了很多将变量更改为字符串等,这是我的第一次尝试:

def perform(text):
    repository = [("","")]
    fdist = nltk.FreqDist(some_variable)
    for c in some_variable:
        repository.append((c, fdist[c]))
    return ' '.join(repository)

但是它给了我以下错误:

Traceback (most recent call last):
  File "<pyshell#120>", line 1, in <module>
    qe = perform(entfile2)
  File "<pyshell#119>", line 14, in perform
    return ' '.join(repository)
TypeError: sequence item 0: expected string, tuple found

如何将列表'存储库'写入文件的任何想法?谢谢!

3 个答案:

答案 0 :(得分:1)

在将元组传递给join()

之前将其转换为字符串

我已经相当彻底地重新安排了这个,这样:

  1. 您的功能现在是一个发电机(内存要求较低)
  2. 传入所需的格式 - 它返回您要求返回的格式
  3. 我猜some_variable是一个可报告的文本子集?
  4. def perform(seq, tell=None, fmt=tuple):
        """
        @param seq:  sequence, items to be counted (string counts as sequence of char)
        @param tell: sequence, items to report on
        @param fmt:  function(item,count) formats output
        """
        # count unique items
        fdist = nltk.FreqDist(seq)
    
        if tell is None:
            # report on all seen items
            for item,num in fdist.iteritems():
                yield fmt(item,num)
        else:
            # report on asked-for items
            for item in tell:
                try:
                    yield fmt(item,fdist[item])
                except KeyError:
                    # tell contained an item not in seq!
                    yield fmt(item,0)
    
    # write to output file
    fname = 'c:/mydir/results.txt'
    with open(fname, 'w') as outf:
        outf.write(' '.join(perform(text, some_variable, ','.join)))        
    

答案 1 :(得分:1)

如果您想在磁盘上存储字典,请使用shelve

import shelve

def get_repository(filename='repository'):
    # stores it's content on the disk
    store = shelve.DbfilenameShelf(filename)

    if not store: 
        # if it's empty fill it
        print 'creating fdist'
        # fdist = nltk.FreqDist(some_variable)
        fdist = dict(hello='There')
        store.update(fdist)
    return store

print get_repository()
# creating fdist
# {'hello': 'There'}
print get_repository()
# {'hello': 'There'}

答案 2 :(得分:0)

首先应使用列表推导将元组列表转换为字符串列表,然后使用连接:

list_of_strings = ["(%s,%s)" % c for c in repository]
' '.join(list_of_strings)