2016-05-13 153 views
0

我有一个句子列表,它是我函数的输出。他们看起来像:将函数输出的字符串列表写入文件

["['A', 'little', 'girl', 'spanks', 'her', 'blonde', 'hair', 'Of', 'a', 'twitching', 'nose', 'A', 'cigarette', 'butt.', '$']", 
"['From', 'another', 'town.', '$', 'The', 'arriving', 'train', 'All', 'my', 'sweaty', 'face', 'In', 'a', 'pine', 'tree.']", 
"['In', 'a', 'heavy', 'fall', 'of', 'flakes', 'And', 'timing', 'its', 'wing,', '\\xe2\\x80\\x93', 'A', 'leaf', 'chases', 'wind']",.... 

"['As', 'green', 'melon', 'splits', 'open', 'And', 'cools', 'red', 'tomatoes!', '$', 'In', 'a', 'breath', 'of', 'an']"] 

请原谅句子中的单词。他们只是实验。我想把它们写成文件,只是简单的句子。

我尝试这样做:

def writeFile(sentences): 
    with open("result.txt", "w") as fp: 
     for item in sentences: 
      fp.write("%s\n" % item) 

但我的输出是这样的:

['A', 'little', 'girl', 'spanks', 'her', 'blonde', 'hair', 'Of', 'a', 'twitching', 'nose', 'A', 'cigarette', 'butt.', '$'] 
['From', 'another', 'town.', '$', 'The', 'arriving', 'train', 'All', 'my', 'sweaty', 'face', 'In', 'a', 'pine', 'tree.'] 

我在Python 2编码有人能帮忙吗?

+2

我想你想要的是'用open(....)作为fp:fp.write(''.join(单词在句子中))''。但我无法确定,因为我不确定是否打算在引用的字符串中放入方括号 – ZWiki

+5

为什么要将您的列表串联起来?这会让你做更多的事情变得更困难。你需要修复产生这个输出的函数,这里你没有显示。 –

+1

@ZWiki - 不需要在句子中逐字地进行' - join()'会为你做迭代,即'''.join(句子)'(这与OP完全不同) – dwanderson

回答

0

如果列表的产品的形式:

"['word0', 'word1', ...., 'wordn']" 

然后用eval将其转换为词的list,然后join它造一个句子为:

def writeFile(sentences): 
    with open("result.txt", "w") as fp: 
     for item in sentences: 
      fp.write("{0}\n".format(" ".join(eval(item)))) 

如果该项目已经是单词列表,那么在上面的代码中不需要eval

顺便说一句,如果你爱列表理解和具有功能性,那么你可以这样做:

def writeFile(sentences): 
    with open("result.txt", "w") as fp: 
     fp.write("\n".join(["".join(eval(item)) for item in sentences])) 

不过,如果句子中有太多的项目,因为它可能不是非常有效可能最终会使用巨大的内存。