您好。我想问一下如何将一个句子列表打印成文本文件。我尝试使用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()
文本文件中的当前输出:
的Android
NNPsmartphones
NNSplay
VBPa
DTmajor
JJrole
NNIN
INtoday
NN的
POSworld
NNThe
我想要的文字文件输出:
答案 0 :(得分:0)
而不是:
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 context manager会为你处理。