python_业余学习_分词工具jieba 正则表达式清洗微博文本特殊符号 最大匹配算法

0. 原文学习

原文1学习:文本处理流程——分词
原文2学习数据与步骤
原文3学习:Python正则表达式清洗微博文本特殊符号(网址, @, 表情符等)

1. jieba分词工具的安装

Microsoft Windows [版本 10.0.19042.1466]
(c) Microsoft Corporation。保留所有权利。

C:\Users\LENOVO>pip install jieba
Looking in indexes: http://pypi.douban.com/simple
Collecting jieba
  Downloading http://pypi.doubanio.com/packages/c6/cb/18eeb235f833b726522d7ebed54f2278ce28ba9438e3135ab0278d9792a2/jieba-0.42.1.tar.gz (19.2 MB)
     |████████████████████████████████| 19.2 MB 409 kB/s
  Preparing metadata (setup.py) ... done
Using legacy 'setup.py install' for jieba, since package 'wheel' is not installed.
Installing collected packages: jieba
    Running setup.py install for jieba ... done
Successfully installed jieba-0.42.1

2. 使用jieba分词工具实现分词

原文学习:文本处理流程——分词

import jieba
# 默认基于jieba分词库分词
seg_list = jieba.cut("头大!头大!真头大!毕业设计真令人头大!十个头十个大!", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list))

jieba.add_word("真头大")
jieba.add_word("!")
seg_list = jieba.cut("头大!头大!真头大!毕业设计真令人头大!十个头十个大!", cut_all=False)
print("Modify: " + "/ ".join(seg_list))

在这里插入图片描述

3. 获取微博文本txt版本

原文学习数据与步骤

import pandas as pd
path = 'data/weibo_senti_100k/'
pd_all = pd.read_csv(path + 'weibo_senti_100k.csv')

print('评论数目(总体):%d' % pd_all.shape[0])
print('评论数目(正向):%d' % pd_all[pd_all.label==1].shape[0])
print('评论数目(负向):%d' % pd_all[pd_all.label==0].shape[0])

print(pd_all.sample(20))

在这里插入图片描述
获得的文本如下:
在这里插入图片描述

4. Python正则表达式清洗微博文本特殊符号(网址, @, 表情符等)

原文学习:Python正则表达式清洗微博文本特殊符号(网址, @, 表情符等)

weibo.txt文本如下:
在这里插入图片描述

import os
import re
def clean(text):
    text = re.sub(r"(回复)?(//)?\s*@\S*?\s*(:| |$)", " ", text)  # 去除正文中的@和回复/转发中的用户名
    text = re.sub(r"\[\S+\]", "", text)      # 去除表情符号
    # text = re.sub(r"#\S+#", "", text)      # 保留话题内容
    URL_REGEX = re.compile(
        r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))',
        re.IGNORECASE)
    text = re.sub(URL_REGEX, "", text)       # 去除网址
    text = text.replace("转发微博", "")       # 去除无意义的词语
    text = re.sub(r"\s+", " ", text) # 合并正文中过多的空格
    return text.strip()


# 创建输出文件
if os.path.exists('data/weibo_last.txt'):
    os.remove('data/weibo_last.txt')
fout = open('data/weibo_last.txt', 'a', encoding='utf-8')

if __name__ == '__main__':
    with open('data/weibo.txt', 'r', encoding='utf-8') as fp:
        lists = fp.readlines()
        for ll in lists:
            l = clean(ll)  # 数据清洗
            fout.writelines(l + '\n')  # 写入文件
            # fout.write(l + '\n')  # 写入文件
    fout.close()

去掉网址, @, 表情符等的文本如下:
在这里插入图片描述

5. 再次进行分词,使用前向最大匹配算法

原文学习:文本处理流程——分词

分词sample.txt
在这里插入图片描述

test_file = 'data/train.txt'  # 训练语料
test_file2 = 'data/分词sample.txt'  # 测试语料
test_file3 = 'data/分词result.txt'  # 生成结果
def get_dic(test_file):  # 读取文本返回列表
    with open(test_file, 'r', encoding='utf-8', ) as f:
        try:
            file_content = f.read().split()
        finally:
            f.close()
    chars = list(set(file_content))
    return chars
dic = get_dic(test_file)
def readfile(test_file2):
    max_length = 5

    h = open(test_file3, 'w', encoding='utf-8', )
    with open(test_file2, 'r', encoding='utf-8', ) as f:
        lines = f.readlines()

    for line in lines:  # 分别对每行进行正向最大匹配处理
        max_length = 5
        my_list = []
        len_hang = len(line)
        while len_hang > 0:
            tryWord = line[0:max_length]
            while tryWord not in dic:
                if len(tryWord) == 1:
                    break
                tryWord = tryWord[0:len(tryWord) - 1]
            my_list.append(tryWord)
            line = line[len(tryWord):]
            len_hang = len(line)

        for t in my_list:  # 将分词结果写入生成文件
            if t == '\n':
                h.write('\n')
            else:
                h.write(t + "  ")
    h.close()
readfile(test_file2)

分词result.txt 获得结果如下:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值