有些词可以有不止一种可能的词性 (pos) 标记。 例如。 “Stick”既是名词又是动词。
NLTK 中的 pos 标注器尝试根据上下文猜测正确的标签并仅返回第 1 个猜测。我如何才能获取任何给定单词的所有可能标签的列表?
请您参考如下方法:
长话短说
不,不是默认的 pos_tag 函数。
在龙
对于默认的 pos_tag 函数,这是不可能的。
默认的 pos_tag 函数来自 AveragedPerceptron 对象,它使用 predict() 函数来获取最可能的标签:https://github.com/nltk/nltk/blob/develop/nltk/tag/perceptron.py#L48
该函数返回可能标签列表中的 argmax:
def predict(self, features):
'''Dot-product the features and current weights and return the best label.'''
scores = defaultdict(float)
for feat, value in features.items():
if feat not in self.weights or value == 0:
continue
weights = self.weights[feat]
for label, weight in weights.items():
scores[label] += value * weight
# Do a secondary alphabetic sort, for stability
return max(self.classes, key=lambda label: (scores[label], label))
实际上,如果您更改代码,您的代码将通过让它返回 self.classes 来获取每个可能标签的分数。
但是因为tag()中使用的特征需要前面两个标签作为特征https://github.com/nltk/nltk/blob/develop/nltk/tag/perceptron.py#L156
def tag(self, tokens):
'''
Tag tokenized sentences.
:params tokens: list of word
:type tokens: list(str)
'''
prev, prev2 = self.START
output = []
context = self.START + [self.normalize(w) for w in tokens] + self.END
for i, word in enumerate(tokens):
tag = self.tagdict.get(word)
if not tag:
features = self._get_features(i, word, context, prev, prev2)
tag = self.model.predict(features)
output.append((word, tag))
prev2 = prev
prev = tag
return output
返回 n-best 标签的任务必须将标记器简单的 one-best “贪婪”性质更改为需要光束的东西。
