文本预处理函数定义(dataframe格式下使用apply)

本文是在2020美赛建模C题的文件下使用,如果有想要数据集的朋友可以自行下载或留言

##导入库
import nltk
from nltk.corpus import stopwords

对于预处理函数使用了3中预处理方法,比较粗糙,入门可以使用这个函数进行处理
1.delete stop words(example:)
2.lower all the alpha
3.stem the word(还原词根)
4.split() function to get all the words

###函数定义
def preprocess(text):           #训练可以加入别的东西,自己选择
    tokens = []
    words = text.split(' ')#也就是这个东西如果不是在stop_words中的话,进行一部分操作
    for token in words:  # for token in words,也就是如果不存在一个东西可以使用,
        token = token.lower()
        if token not in stop_words:
                tokens.append(stemmer.stem(token))
    return " ".join(tokens)

上述为函数定义。

而使用apply函数可以对每一行进行预处理

stop_words = stopwords.words("english")
wnl = nltk.WordNetLemmatizer()
stemmer = nltk.SnowballStemmer("english")  #也就是
tokens = []
print(stop_words)
#预处理函数  进行停顿词删除与词根提取
def preprocess(text):           #训练可以加入别的东西,自己选择
    tokens = []
    words = text.split(' ')#也就是这个东西如果不是在stop_words中的话,进行一部分操作
    for token in words:  # for token in words,也就是如果不存在一个东西可以使用,
        token = token.lower()
        if token not in stop_words:
                tokens.append(stemmer.stem(token))
    return " ".join(tokens)
    #得到了一堆列表的列表
print(hair['review_body'][11467])  #测试使用
hair['review_body'] = hair['review_body'].apply(lambda x:preprocess(x)) #apply函数
print(hair['review_body'][11467])  #测试使用

而使用之后的输出大致为此:
在这里插入图片描述
可以看到this,is,it等函数已被删除,已经完成基础的预处理功能

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值