815 文本分析预处理实例

这篇博客介绍了文本预处理的步骤,包括转换为小写、去除标点符号和数字、移除停用词以及词干提取。还展示了如何计算词频、构建词袋模型以及生成2-grams和3-grams。内容涵盖了从基础的文本处理到N-gram的构建,为后续的文本分析打下基础。
摘要由CSDN通过智能技术生成

这是tutorial6的Part ABC,本文对内容进行了一些修改

本次用到的包:

# -*- coding: utf-8 -*-
"""
Created on Fri Mar  4 18:01:58 2022

@author: Pamplemousse
"""


from nltk import sent_tokenize
import string
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer
from nltk.tag import perceptron
from nltk import word_tokenize
from collections import Counter
from nltk import ngrams

这个nltk包好像不用安,跑不动它会提示你要import nltk 然后nltk.install什么什么的,照提示的输入到控制台(就是显示输出结果的地方)内就能自动安装

首先是文本

Sampletext = '123 one two Our modern world is witnessing a growth of online data in a variety of forms. These  includes blogs, social networks, digital libraries and medical records. Much of these sources contain valuable information. For example, emerging opinions in social networks and search trends from search engines consumer purchase behaviour.'

print(Sampletext)

这里的输出我就不贴了,文本里面的123 和 one two是我后来加进去的,为了方便后面去除数字的操作比较直观一点而已。
一般来说我们是从外部读取一个(或多个)文本文件,这里我们直接自定义了

将文本切割为句子的方法

sentences = sent_tokenize(Sampletext)#把文本切割为句子
print(sentences[1:2])#输出第二句

因为第一句里面没有逗号,我就想知道这个句子是以逗号分割还是以句号分割,所以输出的是第二句,结论是以句号分割,至于其他标点符号同学们也可以自己尝试,不过记得使用英文的符号。

下面开始预处理的第一步,将所有的大写字母变成小写,这个操作方便计算单词出现频率,否则对系统来说Our和our是两个单词(这只是一个例子)

# In[3]:

text_lower = Sampletext.lower()#将所有大写转为小写
print(text_lower)

第二步是去掉标点符号,老师使用的代码是在原文的基础上去除标点符号,但我这里是在转为小写文本的基础上去除

# In[4]:

#去掉标点符号
translator = str.maketrans('','',string.punctuation)
text_nopunc = text_lower.translate(translator)
print(text_nopunc)

现在我们得到的还是文本,我们需要把文本切割为单词

#将文本切割为单词
tokens = text_nopunc.split()
print(tokens)

这样我们就得到了许多单词,注意这些单词是有序存储的。

随后对这些单词中的数字进行处理


# In[6]:

#将单词中的数字去掉
tokens_nonumbers = [t for t in tokens if not t.isdigit()]
#将单词中的数字用#代替
tokens_norm_numbers = [t if not t.isdigit() else '#' for t in tokens]

print(tokens_nonumbers)
print(tokens_norm_numbers)

得到的两个输出为
在这里插入图片描述

可以看到只有123被去除/替换,而one two是不会被去除的,可以理解为这种方法只会去除digit而不是数

然后是去除一些英文中的stopwords(大概就是对主题的表达没有很大作用的一些词)

# In[7]:

#去掉stopwords
stoplist = stopwords.words('english')
tokens_nostop = [t for t in tokens_nonumbers if t not in stoplist]
#注意我是用去掉数字的token来做stopwords去除的
print(tokens_nostop)

然后是一个stemming的过程,大概意思就是把复杂的单词转换成简单的形式(但是这种转换结果不一定对)

# In[8]:

#把单词转换为简单形式?
stemmer = SnowballStemmer('english')
print(stemmer.stem("caring"))
#一个例子,让我们知道stemming是做什么的
#这里会输出care

stemmer = SnowballStemmer('english')
tokens_stemmed=[stemmer.stem(t) for t in tokens_nostop]
print(tokens_stemmed)

这里的输出是
在这里插入图片描述

可以看出,很多单词都不是正确的形式,但是似乎不影响理解意思。

就很突然,我们要输出每个单词的词性,这里用的又是原文

# In[9]:

#注明每个单词的词性
tagger = perceptron.PerceptronTagger()
tokens = word_tokenize(Sampletext)
tagged_sentence = tagger.tag(tokens)
print(tagged_sentence)

在这里插入图片描述
咱也不是很懂这些词性是什么啊,如果有懂的请教教我,或者给我偷个链接过来

然后是partB要我们完成的内容
计算这段文本有多少个句子,每个句子有多少个单词,以及一共有多少个单词

n[10]:

#计算句子和单词的数量
document = [s.split() for s in sentences]
num_sentences = len(document)
num_words = 0
for sentence in document:
    print(len(sentence))
    num_words += len(sentence)

print(num_sentences)
print(document)
print(num_words)

在这里插入图片描述
一共四个句子,第一句18个词,第二句10,第三句7,第四句16,共51个词

然后是Part C构建词袋
就很迷惑,前面的预处理完全没有用,就是用初始的文本来做词频统计,那大小写和标点符号都还在里面,很迷惑

于是我学习了一下,换了一种方式,使用的是之前做了变小写和去掉标点的文本做的

# In[11]:

#计算单词出现的次数
freqs = {}
tokens = text_nopunc.split()
for token in tokens:
    freqs[token] = freqs.get(token,0)+1

items = list(freqs.items())#将统计结果存为列表类型
items.sort(key=lambda x:x[1], reverse = True)#降序排序
print(items)

得到的结果是
在这里插入图片描述
这样看起来舒服多了

输出频率最高的单词和频率

# In[12]:

#输出频率最高的单词及其出现次数
print('Most common word: ', items[0][0])
print('Frequency of most common word: ', items[0][1])

Most common word: of
Frequency of most common word: 3

最后是构建2-grams和3-grams

# In[13]:

#构建N-grams
bigrams = []
trigrams = []
for n in range(2,4):
    if n==2:
        bigrams += ngrams(tokens, n)
    else:
        trigrams += ngrams(tokens, n)

print(bigrams)
print(trigrams)

bigrams:

[(‘123’, ‘one’), (‘one’, ‘two’), (‘two’, ‘our’), (‘our’, ‘modern’), (‘modern’, ‘world’), (‘world’, ‘is’), (‘is’, ‘witnessing’), (‘witnessing’, ‘a’), (‘a’, ‘growth’), (‘growth’, ‘of’), (‘of’, ‘online’), (‘online’, ‘data’), (‘data’, ‘in’), (‘in’, ‘a’), (‘a’, ‘variety’), (‘variety’, ‘of’), (‘of’, ‘forms’), (‘forms’, ‘these’), (‘these’, ‘includes’), (‘includes’, ‘blogs’), (‘blogs’, ‘social’), (‘social’, ‘networks’), (‘networks’, ‘digital’), (‘digital’, ‘libraries’), (‘libraries’, ‘and’), (‘and’, ‘medical’), (‘medical’, ‘records’), (‘records’, ‘much’), (‘much’, ‘of’), (‘of’, ‘these’), (‘these’, ‘sources’), (‘sources’, ‘contain’), (‘contain’, ‘valuable’), (‘valuable’, ‘information’), (‘information’, ‘for’), (‘for’, ‘example’), (‘example’, ‘emerging’), (‘emerging’, ‘opinions’), (‘opinions’, ‘in’), (‘in’, ‘social’), (‘social’, ‘networks’), (‘networks’, ‘and’), (‘and’, ‘search’), (‘search’, ‘trends’), (‘trends’, ‘from’), (‘from’, ‘search’), (‘search’, ‘engines’), (‘engines’, ‘consumer’), (‘consumer’, ‘purchase’), (‘purchase’, ‘behaviour’)]

trigrams:
[(‘123’, ‘one’, ‘two’), (‘one’, ‘two’, ‘our’), (‘two’, ‘our’, ‘modern’), (‘our’, ‘modern’, ‘world’), (‘modern’, ‘world’, ‘is’), (‘world’, ‘is’, ‘witnessing’), (‘is’, ‘witnessing’, ‘a’), (‘witnessing’, ‘a’, ‘growth’), (‘a’, ‘growth’, ‘of’), (‘growth’, ‘of’, ‘online’), (‘of’, ‘online’, ‘data’), (‘online’, ‘data’, ‘in’), (‘data’, ‘in’, ‘a’), (‘in’, ‘a’, ‘variety’), (‘a’, ‘variety’, ‘of’), (‘variety’, ‘of’, ‘forms’), (‘of’, ‘forms’, ‘these’), (‘forms’, ‘these’, ‘includes’), (‘these’, ‘includes’, ‘blogs’), (‘includes’, ‘blogs’, ‘social’), (‘blogs’, ‘social’, ‘networks’), (‘social’, ‘networks’, ‘digital’), (‘networks’, ‘digital’, ‘libraries’), (‘digital’, ‘libraries’, ‘and’), (‘libraries’, ‘and’, ‘medical’), (‘and’, ‘medical’, ‘records’), (‘medical’, ‘records’, ‘much’), (‘records’, ‘much’, ‘of’), (‘much’, ‘of’, ‘these’), (‘of’, ‘these’, ‘sources’), (‘these’, ‘sources’, ‘contain’), (‘sources’, ‘contain’, ‘valuable’), (‘contain’, ‘valuable’, ‘information’), (‘valuable’, ‘information’, ‘for’), (‘information’, ‘for’, ‘example’), (‘for’, ‘example’, ‘emerging’), (‘example’, ‘emerging’, ‘opinions’), (‘emerging’, ‘opinions’, ‘in’), (‘opinions’, ‘in’, ‘social’), (‘in’, ‘social’, ‘networks’), (‘social’, ‘networks’, ‘and’), (‘networks’, ‘and’, ‘search’), (‘and’, ‘search’, ‘trends’), (‘search’, ‘trends’, ‘from’), (‘trends’, ‘from’, ‘search’), (‘from’, ‘search’, ‘engines’), (‘search’, ‘engines’, ‘consumer’), (‘engines’, ‘consumer’, ‘purchase’), (‘consumer’, ‘purchase’, ‘behaviour’)]

当然也可以选择保留标点符号,还是看编程的需求嘛。
就是觉得这样好看这样子((`へ´*)ノ)

下班!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

端午节放纸鸢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值