匠心精神 - 良心品质腾讯认可的专业机构-IT人的高薪实战学院

咨询电话:4000806560

【Python 自然语言处理】如何用 NLTK 处理文本?

【Python 自然语言处理】如何用 NLTK 处理文本?

自然语言处理(NLP)是一门计算机科学、人工智能和语言学交叉的学科,它主要涉及计算机对自然语言的理解和生成。Python 自然语言处理包(NLTK)是一种广泛使用的开源工具,它提供了一种处理文本的方法。



1. 安装 NLTK
在使用 NLTK 之前,需要先安装它,可以使用 pip 安装,打开命令行终端,输入以下命令:

```
pip install nltk
```
安装完成后,可以导入模块并使用它的方法。


2. NLTK 中的文本预处理
在进行文本处理之前,需要先进行文本预处理,包括划分单词、删除停用词、词形还原等操作。下面是一些 NLTK 中常用的文本预处理方法。

2.1 分词
分词是将原始文本分成单词的过程,可以使用 NLTK 中的 word_tokenize() 方法来实现,示例代码如下:

```
from nltk.tokenize import word_tokenize

text = "Hello World, this is a sample text for tokenization"
tokens = word_tokenize(text)

print(tokens)
```

2.2 删除停用词
停用词是一个文本中频繁出现但没有实际含义的单词,如“我、你、他”等。可以使用 NLTK 中提供的停用词库进行删除。示例代码如下:

```
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

text = "This is a sample sentence, showing off the stop words filtration."
stop_words = set(stopwords.words("english"))

words = word_tokenize(text)

filtered_sentence = [word for word in words if not word in stop_words]

print(filtered_sentence)
```

2.3 词形还原
词形还原是将单词还原为它们的基本形式(称为词干),如“running”转换为“run”的过程。可以使用 WordNetLemmatizer 类实现。示例代码如下:

```
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize

lemmatizer = WordNetLemmatizer()

text = "This is a sample sentence, showing off the lemmatization."

words = word_tokenize(text)

lemmatized_words = [lemmatizer.lemmatize(word) for word in words]

print(lemmatized_words)
```

3. NLTK 中的文本分析
在进行了文本预处理之后,可以使用 NLTK 中的一些文本分析方法来探索文本的特征。下面是一些常用的文本分析方法。

3.1 词频统计
词频统计是计算文本中单词出现频率的过程。可以使用 FreqDist 类实现。示例代码如下:

```
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist

text = "This is a sample sentence, showing off the frequency distribution."

words = word_tokenize(text)

fdist = FreqDist(words)

print(fdist.most_common(2))
```

3.2 文本分类
文本分类是将文本分成不同的类别的过程,可以使用 NaiveBayesClassifier 类实现。示例代码如下:

```
from nltk.tokenize import word_tokenize
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews

def extract_features_words(text):
    words = word_tokenize(text)
    return dict([(word, True) for word in words])

neg_reviews = [(extract_features_words(movie_reviews.words(fileids=[f])), 'negative') for f in movie_reviews.fileids('neg')]
pos_reviews = [(extract_features_words(movie_reviews.words(fileids=[f])), 'positive') for f in movie_reviews.fileids('pos')]

train_set = neg_reviews[:750] + pos_reviews[:750]
test_set = neg_reviews[750:] + pos_reviews[750:]

classifier = NaiveBayesClassifier.train(train_set)

accuracy = nltk.classify.util.accuracy(classifier, test_set)

print(accuracy * 100)
```


总结
本文介绍了 NLTK 的一些基本用法,包括文本预处理和文本分析。NLTK 在自然语言处理中有着广泛应用,可以用于分析新闻、社交媒体数据、电子邮件等各种形式的文本数据。希望本文对您有所帮助。