2016-12-15 262 views
1

嗨。我想問一下如何將文本列表打印到文本文件中。我嘗試使用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? –

回答

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(),因爲帶上下文管理器會爲你處理。

+0

輸出有效,但是如何從字中刪除()和'' ? – Lily

+0

因此,而不是使用一個單一的線打印的像做(Python2): '在processed_sentence部分: 打印>> FOUT 「%s%S」 %部分,' 逗號以下部分否則重要的是將新行添加到輸出中。這裏的代碼片段應該產生你上面列出的內容。 –