我创建了两个类:一个用于解析命令行参数,另一个用于从停用词文件中获取停用词:
import getopt, sys, re
class CommandLine:
def __init__(self):
opts, args = getopt.getopt(sys.argv[1:],'hs:c:i:I')
opts = dict(opts)
self.argfiles = args
def getStopWordsFile(self):
if '-s' in self.opts:
return self.opts['-s']
class StopWords:
def __init__(self):
self.stopWrds = set()
def getStopWords(self,file):
f = open(file,'r')
for line in f:
val = line.strip('\n')
self.stopWrds.add(val)
f.close()
return self.stopWrds
我想要的是打印停用词集,因此我定义了以下内容:
config = CommandLine()
filee = config.getStopWordsFile()
sw = StopWords()
print sw.getStopWords(filee)
这是命令行:
python Practice5.py -s stop_list.txt -c documents.txt -i index.txt -I
当我运行代码时,我收到了这个错误:
if '-s' in self.opts:
AttributeError: CommandLine instance has no attribute 'opts'
我无法解决的问题是如何从init方法获取opts并在getStopWordFile()方法中使用它。那么这个问题的可能解决方案是什么?
答案 0 :(得分:1)
您忘记在self.
中将opts
添加到__init__
:
class CommandLine:
def __init__(self):
opts, args = getopt.getopt(sys.argv[1:],'hs:c:i:I')
self.opts = dict(opts)
self.argfiles = args
答案 1 :(得分:1)
将以下方法更改为
def __init__(self):
opts, args = getopt.getopt(sys.argv[1:],'hs:c:i:I')
self.opts = dict(opts)
self.argfiles = args