【发布时间】: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该
文本文件中我想要的输出:
- 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