【问题标题】:How to write a list of sentences into text file in Python如何在 Python 中将句子列表写入文本文件
【发布时间】:2017-05-01 08:29:59
【问题描述】:

嗨。我想问一下如何将句子列表打印到文本文件中。我尝试使用 write() 函数来导出如下所示的输出,但我无法像在 python shell 中那样获得输出。


import os
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.tag import pos_tag

def preprocess():

    with open("E:\FYP 2\Error Detection Data\Data\Raw Data\D1.txt", "r") as fin, open("E:\FYP 2\Error Detection Data\Data\Raw Data\D1_edit.txt", "w") as fout:
        for sent in sent_tokenize(fin.read()):
            words = word_tokenize(sent)
            tag = pos_tag(words)
            processed_sentence = [w for w in tag]

            print (processed_sentence)
            print ("\n")

            for i in range(0,len(processed_sentence)-1):
                sentsplit = processed_sentence[i]
                fout.write('\n'.join(sentsplit))

        fin.close()
        fout.close()

preprocess()

文本文件中的当前输出:

安卓

NNP 智能手机

NNSplay

VBPa

DTmajor

JJ角色

NNin

今天

NN的

POS世界

NN该

文本文件中我想要的输出:

  1. Android,NNP 智能手机,NNS 游戏,VBP a,DT 专业,JJ 角色,NN in,IN today,NN's,POS 世界,NN .,.

【问题讨论】:

  • 您可以使用fout.writelines(sentsplit)。您要更改的输出到底是什么?你能告诉我们这产生的文件与你想要产生的文件吗?
  • @PatrickHaugh 我无法上传输出的图像。我只是编辑我的帖子
  • 您希望文件是什么样的?你想要每行都有一个元组吗?你用的是什么版本的python?
  • @PatrickHaugh 感谢您的评论。我只是使用 writelines() 函数编辑我的代码。但似乎文本文件中的输出与python shell中的输出不相似。它只是将所有句子组合在一起。
  • @PatrickHaugh 我希望文件有一个句子列表,每个句子中都有其标记词。我正在使用 Python 3.4

标签: python string list type-conversion


【解决方案1】:

代替:

        for i in range(0,len(processed_sentence)-1):
            sentsplit = processed_sentence[i]
            fout.write('\n'.join(sentsplit))

在python3中尝试:

print(processed_sentence, file=fout)

在 python2 中尝试:

print >> fout, processed_sentence

您也不需要 fout.close() 或 fin.close() 因为 with 上下文管理器会为您处理。

【讨论】:

  • 输出有效,但如何从单词中删除 () 和 ''?
  • 所以不要使用单行进行打印,而是执行类似 (Python2) 的操作:for part in processed_sentence: print >> fout, "%s,%s" % part, 逗号后面的部分很重要,否则会在输出中添加新行。这里的代码 sn-p 应该会产生您上面列出的内容。
猜你喜欢
  • 2020-04-20
  • 1970-01-01
  • 2013-02-18
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
  • 2014-06-27
  • 2014-11-22
  • 1970-01-01
相关资源
最近更新 更多