我需要写一个程序的文本柠檬化(不同形式的单词)。由于我将使用不同的柠檬化库并对它们进行比较,所以我决定使用策略模式。
我的想法是把所有的东西都包装成单个类,并根据柠檬化函数,只改变我的狐猴化方法。
这是我的课:
import re
import types
create_bound_method = types.MethodType
class Lemmatizator(object):
def __init__(self, filename=None, lemmatization=None):
if lemmatization and filename:
self.filename = filename
self.lemmatize = create_bound_method(lemmatization, self)
def _get_text(self):
with open(f'texts/{self.filename}.txt', 'r') as file:
self.text = file.read()
def _split_to_unique(self):
text = re.sub(r'[^\w\s]', '', self.text)
split_text = re.split(r'\s', text)
self.unique_words = set(split_text)
return self.unique_words
def lemmatize(self):
return 'Lemmatize function or text are not found'然后,我创建了我的柠檬化方法:
def nltk_lemmatization(self):
words = {}
for word in self.unique_words:
if word:
words[word] = {
'noun': wnl.lemmatize(word),
'adverb': wnl.lemmatize(word, pos='r'),
'adjective': wnl.lemmatize(word, pos='a'),
'verb': wnl.lemmatize(word, pos='v')
}
return words并试图应用:
nltk_lem = Lemmatizator('A Christmas Carol in Prose', nltk_lemmatization)
nltk_lem.lemmatize()但我收到以下错误:
关于self.unique_words中的单词: AttributeError:'unique_words‘对象没有属性’unique_words‘
怎么了?
发布于 2018-11-27 12:16:47
据我所见,self.unique_words只添加到_split_to_unique(self)函数中的类中。因此,当您调用nltk_lemmatization(self)时,还没有调用_split_to_unique(self),因此,它试图迭代一些不存在的内容。
https://stackoverflow.com/questions/53499012
复制相似问题