让我们检查如何以.lemmatize()编程方式确定方法的第二个参数 。NLTK 具有pos_tag()帮助确定句子中单词上下文的功能 。但是,您首先需要
averaged_perceptron_tagger通过 NLTK 下载器下载资源:
nltk.download('averaged_perceptron_tagger')接下来,导入pos_tag()函数并在一个句子上运行它:
from nltk.tag import pos_tagsample = "Hi, this is a nice hotel."print(pos_tag(word_tokenize(sample)))您会注意到输出是一个对列表 。每对由一个标记及其标记组成,它表示整个文本中标记的上下文 。请注意,标点符号的标签本身就是:
[('Hi', 'NNP'),(',', ','),('this', 'DT'),('is', 'VBZ'),('a', 'DT'),('nice', 'JJ'),('hotel', 'NN'),('.', '.')]你如何解码每个令牌的上下文?这是Web 上所有标签及其相应含义的完整列表 。请注意,所有名词的标签都以“N”开头,所有动词的标签都以“V”开头 。我们可以在方法的第二个参数中使用此信息.lemmatize():
def lemmatize_tokens(stentence):lemmatizer = WordNetLemmatizer()lemmatized_tokens = []for word, tag in pos_tag(stentence):if tag.startswith('NN'):pos = 'n'elif tag.startswith('VB'):pos = 'v'else:pos = 'a'lemmatized_tokens.Append(lemmatizer.lemmatize(word, pos))return lemmatized_tokenssample = "Legal authority constitutes all magistrates."print(lemmatize_tokens(word_tokenize(sample)))上面代码的输出如下:
['Legal', 'authority', 'constitute', 'all', 'magistrate', '.']此输出是预期的,其中“constitutes”和“magistrates”已分别转换为“constitute”和“magistrate” 。
第 3 步:数据清理准备数据的下一步是清理数据并删除任何对您的分析没有意义的内容 。从广义上讲,我们将考虑从您的分析中删除标点符号和停用词 。
删除标点符号是一项相当容易的任务 。该库的punctuation对象string包含所有英文标点符号:
import stringprint(string.punctuation)此代码片段的输出如下:
'!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~'为了从标记中删除标点符号,您可以简单地运行:
for token in tokens:if token in string.punctuation:# Do something接下来,我们将专注于删除停用词 。停用词是语言中常用的词,如“I”、“a”和“the”,在分析文本时对文本几乎没有意义 。因此,我们将从分析中删除停用词 。首先,stopwords从 NLTK 下载器下载资源:
nltk.download('stopwords')一旦下载完成后,进口stopwords从nltk.corpus和使用.words()方法与“英语”作为参数 。这是一个包含 179 个英语停用词的列表:
from nltk.corpus import stopwordsstop_words = stopwords.words('english')我们可以将词形还原示例与本节中讨论的概念结合起来创建以下函数,clean_data() 。此外,在比较一个词是否是停用词列表的一部分之前,我们将其转换为小写 。这样,如果停止词出现在句子的开头并且大写,我们仍然会捕获它:
def clean_data(tokens, stop_words = ()):cleaned_tokens = []for token, tag in pos_tag(tokens):if tag.startswith("NN"):pos = 'n'elif tag.startswith('VB'):pos = 'v'else:pos = 'a'lemmatizer = WordNetLemmatizer()token = lemmatizer.lemmatize(token, pos)if token not in string.punctuation and token.lower() not in stop_words:cleaned_tokens.append(token)return cleaned_tokenssample = "The quick brown fox jumps over the lazy dog."stop_words = stopwords.words('english')clean_data(word_tokenize(sample), stop_words)该示例的输出如下:
['quick', 'brown', 'fox', 'jump', 'lazy', 'dog']如您所见,标点符号和停用词已被删除 。
词频分布现在您已经熟悉了 NLP 中的基本清理技术,让我们尝试找出文本中单词的频率 。在本练习中,我们将使用古腾堡免费提供的童话故事
推荐阅读
- 用python帮别人写了个文字识别程序
- 3个提升Python运行速度的方法,很实用
- 手把手教你编写Python抢购脚本
- SpringBoot中的Controller详解
- Python生成遍历暴力破解密码,实战的效果差强人意了
- 二手房买卖合同中的注意事项
- 购物中心设计中的注意事项
- 详解Python软件安装教程和配置,小白都能看懂的教程,值得收藏
- 三国演义中的孔明是诸葛亮吗?诸葛和孔明是一个人吗_2
- 什么的诸葛孔明?三国演义中的孔明是诸葛亮吗_1
