2016-05-13 135 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])) 

不過,如果句子中有太多的項目,因爲它可能不是非常有效可能最終會使用巨大的內存。