如何在Python中将文本列表写入文本文件

问题描述:


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


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的

POSwor​​ld

NNThe

输出,我想在文本文件中:

  1. Android,NNP智能手机,NNS play,VBP a,DT主要,JJ角色,NN in,今天,NN,POS世界,NN。
+0

你可以使用'fout.writelines(sentsplit)'。你想要改变的输出是什么?你能告诉我们这个文件产生与你想产生的文件吗? –

+0

@PatrickHaugh我无法上传输出图像。我只是编辑我的文章 – Lily

+0

你想让这个文件看起来像什么?你想每行都有一个元组吗?你使用的是什么版本的Python? –

相反的:

 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(),因为带上下文管理器会为你处理。

+0

输出有效,但是如何从字中删除()和'' ? – Lily

+0

因此,而不是使用一个单一的线打印的像做(Python2): '在processed_sentence部分: 打印>> FOUT “%s%S” %部分,' 逗号以下部分否则重要的是将新行添加到输出中。这里的代码片段应该产生你上面列出的内容。 –