2011-01-11 95 views
2

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

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 

任何想法如何写列表“存储库'到一个文件?谢谢!

+1

你应该更好地解释什么是你要回报,这格式的字符串?你想稍后检索元组吗? – 2011-01-11 02:08:47

+0

是应该是某种持久性缓存的存储库? – 2011-01-11 02:11:09

回答

0

你应该元组的列表使用列表解析首先转换为字符串列表,然后以后使用join:

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

将它们加入()

之前转换的元组字符串

我已经相当大幅度重排本,使得:

  1. 现在你的函数是发电机(更低的内存需求)
  2. 传递所需的格式 - 它返回任何格式,你要求它返回
  3. 我猜some_variable是可报告的文本子集?

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

在要存储在磁盘上的字典的情况下,使用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'}