2016-03-22 41 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) 
相关问题