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

人工智能 – 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)
类型是:  

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

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

(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。

你可能感兴趣的:(人工智能,NLP,stopwords,机器学习,人工智能)