【问题标题】:Writing List of Strings Outputted by Function to a File将函数输出的字符串列表写入文件
【发布时间】: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 之外的所有内容)

标签: python list file indexing


【解决方案1】:

如果您的列表中的项目是以下形式:

"['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))))

如果item已经是单词列表,那么上面代码中就不需要eval了。

顺便说一句,如果您喜欢列表理解和功能,那么您可以这样做:

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

但是如果 sentences 中有太多的项目,它可能效率不高,因为它最终可能会占用大量内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-15
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多