input_str = """
There are some people who think love is sex
And marriage
And six o'clock-kisses
And children,
And perhaps it is,
Miss Lester.
But do you know what I think?
I think love is a touch and yet not a touch
"""
input_str = input_str.lower()
print(input_str)
结果如下:5 U- ^/ I1 A+ |7 O, b+ l
; i- _7 X& o7 x( e m* y8 Z# K 2、删除或者提取文本中出现的数字 d" k4 t2 f- Q& v9 T' F# G 如果文本中的数字与文本分析无关的话,那就删除这些数字。) d5 H4 X3 C6 ~5 [# G7 D( H
结果如下: % ~: u2 X9 f% c2 ?4 \& f& g 6 y9 o3 s) I. f4 T4 L# n 可以看到文本中乱七八糟的符号都被滤除了,用正则表达式过滤文本中的标点符号,如果空白符也需要过滤,可以使用 r'[^\w]'。原理很简单:在正则表达式中,\w 匹配字母或数字或下划线或汉字(具体与字符集有关),^\w表示相反匹配。8 n7 |) _+ g5 ]' Y, R- r 4、删除两端无用的空格 Z6 D& u$ m5 c+ D. Y" z
# 从Github下载停用词数据 https://github.com/zhousishuo/stopwords
import jieba
import re
# 读取用于测试的文本数据 用户评论
with open('comments.txt') as f:
data = f.read()
# 文本预处理 去除一些无用的字符 只提取出中文出来
new_data = re.findall('[\u4e00-\u9fa5]+', data, re.S)
new_data = "/".join(new_data)
# 文本分词 精确模式
seg_list_exact = jieba.cut(new_data, cut_all=False)
# 加载停用词数据
with open('stop_words.txt', encoding='utf-8') as f:
# 获取每一行的停用词 添加进集合
con = f.read().split('\n')
stop_words = set()
for i in con:
stop_words.add(i)
# 列表解析式 去除停用词和单个词
result_list = [word for word in seg_list_exact if word not in stop_words and len(word) > 1]
result_list