使用Python NLTK实现N-Grams--一步一步的指南

852 阅读1分钟

在本教程中,我们将讨论n-grams的含义以及如何在Python编程语言中实现n-grams。


了解N-grams

文本n-grams通常被用于自然语言处理和文本挖掘。它本质上是一串同时出现在同一窗口的词。

当计算N-grams时,你通常会提前一个单词(尽管在更复杂的情况下,你可以移动N个单词)。N-grams可用于各种目的。

例如,在创建语言模型时,N-grams不仅被用来创建单字模型,还被用来创建大字和三字模型。

谷歌和微软已经创建了网络规模的语法模型,可用于各种活动,如拼写纠正、连字符和文本总结。


在Python中实现n-grams

ngrams 为了实现n-grams,使用了nltk 中的函数,它将执行所有的n-gram操作:

from nltk import ngrams
sentence = input("Enter the sentence: ")
n = int(input("Enter the value of n: "))
n_grams = ngrams(sentence.split(), n)
for grams in n_grams:
    print(grams)

输出样本

Enter the sentence: Let's test the n-grams implementation with this sample sentence! Yay!
Enter the value of n: 3
("Let's", 'test', 'the')
('test', 'the', 'n-grams')
('the', 'n-grams', 'implementation')
('n-grams', 'implementation', 'with')
('implementation', 'with', 'this')
('with', 'this', 'sample')
('this', 'sample', 'sentence!')
('sample', 'sentence!', 'Yay!')


请看结果是多么的惊人!你可以对一些句子尝试使用相同的代码,编码愉快!😇