n-gram 是一个最多包含 n 个元素的序列,这些元素从由它们组成的序列(通常是字符串)中提取而成。一般来说,n-gram 的“元素”可以是字符、音节、词,甚至是像“A”“T”“G”“C”等表示 DNA 序列的符号。
将单词条的概念扩展到多词条构成的 n-gram,NLP 流水线就可以保留语句词序中隐含的很多含义。例如,否定词“not”就会和它所属的相邻词在一起。如果分词不考虑 n-gram,那么“not”就会自由漂移,而不会固定在某几个词周围,其否定的含义可能就会与整个句子甚至整篇文档,而不是只与某几个相邻词关联,从而造成误导。
from nltk.util import ngrams
import re
sentence = """Thomas Jefferson began building Monticello at the age of 26."""
pattern = re.compile(r"([-\s.,;!?])+")
tokens = pattern.split(sentence)
tokens = [x for x in tokens if x and x not in '- \t\n.,;!?']
print(list(ngrams(tokens, 2)))
print(list(ngrams(tokens, 3)))
# 将允许nlp流水线的后续阶段预期输入的数据类型保持一致,即都是字符串序列
two_grams = list(ngrams(tokens, 2))
print([" ".join(x) for x in two_grams])