【发布时间】:2016-05-13 18:09:13
【问题描述】:
我有一个句子列表,它们是我的函数的输出。它们看起来像:
["['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 进行编码。有人可以帮忙吗?
【问题讨论】:
-
我想你想要的是
with open(....) as fp: fp.write(' '.join(word for word in sentences))。但我不能确定,因为我不确定你是否打算将方括号放在引用的字符串中 -
你为什么要把你的名单串起来?这将使做你想做的事变得更加困难。您需要修复产生此输出的函数,此处未显示。
-
@ZWiki - 无需执行
word for word in sentences-join()将为您完成迭代,即' '.join(sentences)(这都是除了 OP 之外的所有内容)