Python 属性错误:';文件';对象没有属性';拆下';
我正在运行此脚本,但不断得到Python 属性错误:';文件';对象没有属性';拆下';,python,file-io,Python,File Io,我正在运行此脚本,但不断得到 AttributeError:'file'对象没有属性'remove' 错误。由于问题中缺少错误的确切跟踪,我猜失败是由于调用了ss.remove()。从这段代码来看,ss似乎是一个文件句柄,而且(正如错误提示的那样)文件对象不支持remove()方法 如果要删除该文件,可以使用os.remove(filepath),但此代码似乎没有这样做。现在,代码正在尝试从文件中删除单词(这种操作不受支持) 如果要从文件中删除单词,一种简单的方法是开始创建另一个仅包含所需信息
AttributeError:'file'对象没有属性'remove'
错误。由于问题中缺少错误的确切跟踪,我猜失败是由于调用了
ss.remove()
。从这段代码来看,ss
似乎是一个文件句柄,而且(正如错误提示的那样)文件对象不支持remove()
方法
如果要删除该文件,可以使用os.remove(filepath)
,但此代码似乎没有这样做。现在,代码正在尝试从文件中删除单词(这种操作不受支持)
如果要从文件中删除单词,一种简单的方法是开始创建另一个仅包含所需信息的文件(如临时文件),处理完成后,用新生成的文件替换旧文件(并可能在最后删除临时文件)
如果要从数据中排除stopwords
,可以将数据保存在列表中,如下所示:
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"
注意,我们在写模式下打开了输出文件。
还请注意,此代码不保留单词之间的空格数,因为它将行转换为列表,然后从这些单词再次构造行。如果这是一个问题,我认为您可能需要处理字符串,而不是将其拆分为一个列表。我猜OP希望从文件中删除停止字。要执行此操作,请尝试:
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')
我真希望这能让你高兴。如果没有,请留下更详细的注释。此代码段正在从test.txt文件读取文本,并在删除停止字后将相同的文本写入“cde.txt”文件。 这可能对你有帮助
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))
你真正想要实现什么?我想从file@saicharankandibanda你的问题是什么?谢谢你的回答,我添加了以下代码,并再次运行脚本,使用open('cde.txt','r+')作为ss:for-line-in-ss:for-word-in-xrange(len(line.split()):if-line[word]in-stopwords.words('english'):line.remove(word)ss.write(line),但我现在得到以下错误回溯(最近一次调用是最后一次):文件“read.py”,第21行,在line.remove(word)中AttributeError:'str'对象没有属性'remove',抱歉,伙计,我的代码有点马虎,现在应该没事了Heyy,现在我收到了这个错误..回溯(最近一次调用):文件“read.py”,第22行,在parts中。remove(word)ValueError:list.remove(x):x不在list@saicharankandibanda现在试试?
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)