人工智能 -- NLP:文本去掉停用词stopwords

本文详细介绍使用jieba分词及停用词过滤进行文本预处理的方法,通过具体实例展示了如何去除文本中的停用词,并提供了处理大规模文本数据的函数封装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

人工智能 – NLP:文本去掉停用词stopwords

前言

为了彻底搞懂过程本质,本博文写的非常细!

说明:本文内容分两部分:

  • 先从 1.分析过程。以一个字符串str = "的,,,大家好,天宫一号我们年,&*'-"为例说明。
  • 再以 2.封装成普遍使用的函数。来实战处理文本./data/sports_news.csv ----- 字符串列表遍历

1、分析过程

(1)准备停用词
import pandas as pd
import jieba

"""
1.准备停用词
"""
stopwords = pd.read_csv("data/stopwords.txt", index_col=False, quoting=3, sep='\t', names=['word'], encoding='utf-8')
print(stopwords.head(5), '\n')
print(stopwords['word'].head(5), '\n')

print(stopwords['word'].values)
print('类型是:', type(stopwords['word'].values), '\n')

print(stopwords['word'].tolist())
print('类型是:', type(stopwords['word'].tolist()), '\n')

print(stopwords['word'].values.tolist())
print('类型是:', type(stopwords['word'].values.tolist()), '\n')

运行结果:

C:\Python\Anaconda3\python.exe C:/AI/AnacondaProject/kaggle/5-6.NLP/testNLP.py
  word
0    !
1    "
2    #
3    $
4    % 

0    !
1    "
2    #
3    $
4    %
Name: word, dtype: object 

['!', '"', '#', '$', '%', '&',(此处省略)]   # 注释:在jupyter notebook运行结果:array(['!', '"', '#', '$', '%', '&',(此处省略)] , dtype=object)
类型是: <class 'numpy.ndarray'> 

['!', '"', '#', '$', '%', '&',(此处省略)] 
类型是: <class 'list'> 

['!', '"', '#', '$', '%', '&',(此处省略)] 
类型是: <class 'list'> 
(2)数据获取。数据处理。

数据获取:实际中要用padas读取并存储成 字符串列表。
下面:以一个字符串str = "的,,,大家好,天宫一号我们年,&*’-"为例说明。同理:处理字符串列表遍历即可。

"""
2.数据获取str
"""
str = "的,,,大家好,天宫一号我们年,&*'-"


"""
3.数据处理
"""
#(1)jieba分成
sges_list = jieba.lcut(str)
print(sges_list, '\n')

#(2)去停用词后的new_segs_list:
# 写法1:
new_segs_list = [word for word in sges_list if word not in stopwords['word'].values]
print(new_segs_list, '\n')

# 写法2:
new_segs_list = [word for word in sges_list if word not in stopwords['word'].tolist()]
print(new_segs_list, '\n')

# 写法3:
new_segs_list = [word for word in sges_list if word not in stopwords['word'].values.tolist()]
print(new_segs_list, '\n')

运行结果:

['的', ',', ',', ',', '大家', '好', ',', '天宫', '一号', '我们', '年', ',', '&', '*', "'", '-'] 

['天宫', '一号'] 

['天宫', '一号']

['天宫', '一号']

2、封装成函数

import pandas as pd
import jieba

"""
去停用词stopwords
:param list content_lines: 将被处理文本的data
:param list new_content_lines: 存储处理好的data,默认=[]
:return list new_content_lines:  存储处理好的data
"""
def preprocess_text(content_lines, new_content_lines=[]):
    stopwords = pd.read_csv("data/stopwords.txt", index_col=False, quoting=3, sep='\t', names=['stopword'], encoding='utf-8')
    stopwords = list(stopwords['stopword'].values)
    
    for line in content_lines:
        segs_line = jieba.lcut(line)
        new_line = [word for word in segs_line if word not in stopwords]
        new_content_lines.append(new_line)
    return new_content_lines

# 数据准备
df_sports = pd.read_csv("./data/sports_news.csv", encoding='utf-8')
df_sports = df_sports.dropna()
sports = df_sports.content.values.tolist()[:200] # 取前200条数据。实际中可用20000条数据

# 数据处理
sentences = []
preprocess_text(sports, sentences)

# test
print(sentences)

运行结果:

[ ['中新网', '深圳', '日电', ' ', '郑小红', '2019', '深圳'(此处省略)],
  ['王蔷', '岁', '天津', '纯真', '性格', '颇受欢迎',(此处省略)],
  ['寒冷', '冬季', '并未', '挡住', '奔跑', '热情'', (此处省略)],
  ......(此处省略两万字)......
工程思想:

实际上,上面的数据获取,处理数据等,若被用的频率多,可视情况各自封装成一个function,然后也可统一封装成一个class。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值