NLP-中文文本去除标点符号

  • 简单记录一下中文文本如何去除标点和特殊符号的问题。。。

目录


一、回顾一下英文如何去除符号等预处理问题

①去除特殊符号
def isSymbol(inputString):
    return bool(re.match(r'[^\w]', inputString))
②去除数字
def hasNumbers(inputString):
    return bool(re.search(r'\d', inputString))
③词形归一
from nltk.stem import WordNetLemmatizer
wordnet_lemmatizer = WordNetLemmatizer()
④停止词
from nltk.corpus import stopwords
stop = stopwords.words('english')
⑤将上述内容综合
def check(word):
    """
    如果需要这个单词,则True
    如果应该去除,则False
    """
    word= word.lower()
    if word in stop:
        return False
    elif hasNumbers(word) or isSymbol(word):
        return False
    else:
        return True

# 把上面的方法综合起来
def preprocessing(sen):
    res = []
    for word in sen:
        if check(word):#如果word为True的话则进行词形归一
            res.append(wordnet_lemmatizer.lemmatize(word))
    return res

接下来直接调用preprocessing()完成数据的预处理:

X_train = [preprocessing(x) for x in X_train]
X_test = [preprocessing(x) for x in X_test]

二、中文文本去除标点符号

1.背景知识

  • (1)使用 zhon.hanzi.punctuation函数实现。
  • (2)其中zhon是一个python库,它提供了在中文文本处理中常用的几个功能函数,一共包含四个模块: zhon.hanzizhon.pinyinzhon.zhuyinzhon.cedict
  • (3)其中实现去除标点的功能在 zhon.hanzi模块中,我们使用 from zhon.hanzi import punctuation进行调用。
  • (4)其中 zhon.hanzi.punctuation函数是 zhon.hanzi.non_stopszhon.hanzi.stop两个函数的结合。

zhon.hanzi.non_stops
它包含中文标点符号,不包括用作停止的标点符号。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏

zhon.hanzi.stops
包含起着停止作用的符号: !?。。

了解更多Zhon内容请点击链接:Zhon

2.示例说明1:使用Zhon库中的符号集

①命令行中安装Zhon库

pip install zhon

②代码
import re
from zhon.hanzi import punctuation
from zhon.hanzi import non_stops
from zhon.hanzi import stops
corpus='花!呗/期?免,息.---蚂!蚁/花呗?期免stops息,什么。意思??'
print(corpus)
string1 = re.sub(r"[%s]+" %punctuation, "",corpus)#去除, ! ? 。
string2 = re.sub(r"[%s]+" %non_stops, "",corpus)#去除,
string3 = re.sub(r"[%s]+" %stops, "",corpus)#去除! ? 。
print(string1)
print(string2)
print(string3)
③结果

这里写图片描述

④问题说明

通过实验发现,利用Zhon库中的上述只能去除, 。 !?四种符号,而且这四种符号必须是中文符号,无法去除英文符号,无法达到预期结果。。。

3.示例说明2:自定义特殊符号集进行去除

使用自定义的符号集,用于去除想去除的符号,保留对实验有用的符号。

import re
corpus='花呗***期免息!   蚂蚁花呗。***期免息什么意思?'
print(corpus)
string = re.sub("[\s+\.\!\/_,$%^*(+\"\']+|[+——!,。?、~@#¥%……&*()]", "",corpus)
print(string)

结果:
这里写图片描述

  • 15
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值