2016-03-22 42 views
-1
from nltk.corpus import stopwords 
print "starting to read \n" 

fw=open('cde.txt','w'); 

with open('test.txt') as fp: 
    for line in fp: 
       fw.write('\n') 
       fw.write(line) 
fp.close() 
fw.close() 

print "\ndone with writing \n" 

print "starting to print from another file \n" 

with open('cde.txt','r+') as ss: 
    for line in ss: 
     for word in line.split(): 
       if word in stopwords.words('english'): 
         #ss.write(line.remove(word)) 
         ss.remove(word) 

#print line.rstrip() 
ss.close() 

#for word in line.split(): 

print "done with printing from another file" 

我運行此腳本,但不斷收到AttributeError的: '文件' 對象有沒有屬性 '刪除'

AttributeError: 'file' object has no attribute 'remove' 

錯誤。

+3

你究竟想實現什麼? –

+0

[相關](http://stackoverflow.com/questions/21005921/deleting-a-specific-word-from-a-file-in-python) – Idos

+0

我想從文件中刪除停用詞 – sk79

回答

0

由於錯誤的確切軌跡從問題中遺漏,我猜想失敗是由於致電ss.remove()。從此代碼ss似乎是一個文件句柄,並且(如錯誤所示)文件對象不支持remove()方法。

如果你想刪除文件,你可以使用os.remove(filepath),但這段代碼似乎沒有這樣做。現在代碼試圖從文件中刪除單詞(這不是這樣的支持操作)。

如果你想刪除文件中的文字,一個簡單的方法是開始創建另一個只包含所需信息的文件(如臨時文件),並且在處理結束後,用舊文件替換這個新生成的文件(並可能在最後刪除臨時文件)。

如果你想從數據中排除stopwords,你可以保持數據的列表,像這樣的:我們在寫模式打開輸出文件

with open('cde.txt.cleared', 'w+') as output: 
    with open('cde.ext', 'r+') as ss: 
     for line in ss: 
      words = line.strip().split() 
      for word in words: 
       if word in stopwords.words('english'): 
        words.remove(word) 
      output.write(' '.join(words) + '\n') 

注意。 另請注意,此代碼不會保留單詞之間的空格數,因爲它將該行轉換爲列表,然後再從這些單詞中構造該行。如果這是一個問題,我認爲你可能需要處理字符串,而不是將它們分成列表。

0

我猜OP想從文件中刪除停用詞。要做到這一點,請嘗試:

for line in ss: 
    parts = line.split() 
    for word in xrange(len(parts)): 
     if parts[word] in in stopwords.words('english'): 
      parts.remove(parts[word]) 

    ss.write(' '.join(parts)) 

我確實希望這種類型的你。如果沒有,請留下更詳細的評論。

+0

感謝您的回覆,我添加了下面的代碼,並再次運行腳本 與開放('cde.txt','r +')爲ss: 行ss: 在xrange(len(行。分裂())): 如果行[文字]在stopwords.words( '英語'): line.remove(字) ss.write(線) 但我得到下面的錯誤現在 回溯(最近調用最後一個): 文件「read.py」,第21行,在 line.remove(word) AttributeError:'str'object has no attribute'remove' – sk79

+0

對不起,matey,有點草率的codi ng對我來說,現在應該沒問題 – hd1

+0

heyy, 現在我收到了這個錯誤.. 回溯(最近通話最後一個): 文件 「read.py」 22行,在 parts.remove(字) ValueError異常:list.remove(X):X不在列表中 – sk79

0

該代碼片段正在讀取test.txt文件中的文本,並在刪除停用詞後將相同的文本寫入「cde.txt」文件。 這可能會幫助你。

linetext=[] 
for line in ss: 
    line1=[] 
    for word in line.split(): 
     if word not in stopwords.words('english'): 
      line1.append(word) 

    linetext.append(" ".join(line1)) 
    linetext.append('\n') 
with open('cde.txt','wb') as fw: 
    fw.writelines(linetext) 
相關問題