文本预处理(text preprocess)总结

在任何机器学习任务中,清理(cleaning )或预处理(preprocessing)数据与模型构建同样重要,甚至更重要。 当涉及文本等非结构化数据时,这个过程就更加重要。

1. 小写化(Lower Casing)

小写是一种常见的文本预处理技术。 这个想法是将输入文本转换为相同的大小写格式,以便以相同的方式处理 'text'、'Text' 和 'TEXT'。

    def lower_casing(self, text):return text.lower()

2. 删除标点符号(Removal of Punctuations)


另一种常见的文本预处理技术是从文本数据中删除标点符号。 这又是一个文本标准化过程,将有助于处理“hurray”和“hurray!” 以同样的方式。

    #     PUNCT_TO_REMOVE = """!"#$%&\'()*+,-./:;<=>?@[\\]^_{|}~`‘"""def remove_punctuation(self, text):return text.translate(str.maketrans('', '', self.PUNCT_TO_REMOVE))

3. 删除停用词(Removal of stopwords)


停用词是语言中常见的单词,如“the”、“a”等。 大多数时候它们可以从文本中删除,因为它们不为下游分析提供有价值的信息。 在像词性标记这样的情况下,我们不应该删除它们,因为它们提供了有关 POS 的非常有价值的信息。

    def remove_stopwords(self, text):"""custom function to remove the stopwords"""return " ".join([word for word in str(text).split() if word not in self.STOPWORDS])

4. 删除常用词(Removal of Frequent words)


在前面的预处理步骤中,我们根据语言信息删除了停用词。 但是,如果我们有一个特定领域的语料库,我们可能还会有一些对我们来说不太重要的频繁出现的单词。

所以这一步就是去除给定语料库中的频繁出现的单词。 如果我们使用 tfidf 之类的东西,就会自动解决这个问题。

from collections import Counter
cnt = Counter()
for text in df["text"].values:for word in text.split():cnt[word] += 1cnt.most_common(10)

5. 删除不经常用的词(Removal of Rare words)


这与之前的预处理步骤非常相似,但我们将从语料库中删除稀有单词。

n_rare_words = 10
RAREWORDS = set([w for (w, wc) in cnt.most_common()[:-n_rare_words-1:-1]])
def remove_rarewords(text):"""custom function to remove the rare words"""return " ".join([word for word in str(text).split() if word not in RAREWORDS])df["text"] = df["text"].apply(lambda text: remove_rarewords(text))

6. 词干提取(Stemming)


词干提取是将词形变化(或有时派生)的单词还原为其词干、词根或词根形式的过程

例如,如果语料库中有两个单词walks和walking,那么词干提取就会对后缀进行词干处理,使它们成为walking。 但在另一个例子中,我们有两个单词 console 和 consoling,词干分析器将删除后缀并使它们成为 consol,这不是一个正确的英语单词。

有多种类型的词干算法可用,其中最著名的一种是广泛使用的 porter 词干分析器。 我们可以使用 nltk 包来实现同样的目的。

    #  self.stemmer = PorterStemmer()def stem_words(self, text):return " ".join([self.stemmer.stem(word) for word in text.split()])

7. 词形还原(Lemmatization)


词形还原与词干提取类似,将词形变化的单词减少到词干,但不同之处在于它确保词根(也称为词条)属于该语言。

因此,这一过程通常比词干提取过程慢。 因此,根据速度要求,我们可以选择使用词干提取或词形还原。

让我们使用 nltk 中的 WordNetLemmatizer 来对句子进行词形还原

    #  self.lemmatizer = WordNetLemmatizer()def lemmatize_words(self, text):return " ".join([self.lemmatizer.lemmatize(word) for word in text.split()])

8. 删除表情符号(Removal of Emojis)


随着社交媒体平台的使用越来越多,表情符号在我们日常生活中的使用也呈爆炸式增长。 也许我们可能需要删除这些表情符号以进行一些文本分析。

感谢这段代码,请在下面找到一个辅助函数,从我们的文本中删除表情符号。

# Reference : https://gist.github.com/slowkow/7a7f61f495e3dbb7e3d767f97bd7304b
def remove_emoji(string):emoji_pattern = re.compile("["u"\U0001F600-\U0001F64F"  # emoticonsu"\U0001F300-\U0001F5FF"  # symbols & pictographsu"\U0001F680-\U0001F6FF"  # transport & map symbolsu"\U0001F1E0-\U0001F1FF"  # flags (iOS)u"\U00002702-\U000027B0"u"\U000024C2-\U0001F251""]+", flags=re.UNICODE)return emoji_pattern.sub(r'', string)remove_emoji("game is on 🔥🔥")

9. 删除表情符号(Removal of Emoticons)


https://github.com/NeelShah18/emot/blob/master/emot/emo_unicode.py

def remove_emoticons(text):emoticon_pattern = re.compile(u'(' + u'|'.join(k for k in EMOTICONS) + u')')return emoticon_pattern.sub(r'', text)remove_emoticons("Hello :-)")

10. 替换或删除Http url

     def remove_urls(self, text):url_pattern = re.compile(r'https?://\S+|www\.\S+')return url_pattern.sub(r'', text)def replace_http_url(self, text,  word = "urladd"):return re.sub(r'https?://\S+|www\.\S+', word, text)

11. 替换邮件地址

    def replace_email_id(self, text,  word = "emailadd"):return re.sub(r"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})", word,text)

12.  替换数字

主要是为了较低输入的维度

    def replace_digit(self, text,  word = "digitadd"):return re.sub('\d+', word, text)

13. 删掉多余空格和换行

    def remove_extra_space(self, text):return re.sub(' +', ' ', text)def remove_line_break_space(self, text):# return text.replace('\n', ' ').replace('\r', '')return " ".join([word for word in text.split()])

14. 提取html标签里内容并删除

    def remove_html(self, text):return BeautifulSoup(text, features='html5lib').text

15. 缩写还原

# import library
import contractions
# contracted text
text = '''I'll be there within 5 min. Shouldn't you be there too? I'd love to see u there my dear. It's awesome to meet new friends.We've been waiting for this day for so long.'''# creating an empty list
expanded_words = []    
for word in text.split():# using contractions.fix to expand the shortened wordsexpanded_words.append(contractions.fix(word))   expanded_text = ' '.join(expanded_words)
print('Original text: ' + text)
print('Expanded_text: ' + expanded_text)

完整代码

from bs4 import BeautifulSoup
import lxml
import re
from nltk.corpus import stopwords
import nltk
from nltk.stem.porter import PorterStemmer
from spellchecker import SpellChecker
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
import contractionsclass text_preprocessing():PUNCT_TO_REMOVE = """!"#$%&\'()*+,-./:;<=>?@[\\]^_{|}~`‘"""def __init__(self):nltk.download('stopwords')self.STOPWORDS = set(stopwords.words('english'))self.stemmer = PorterStemmer()nltk.download('wordnet')self.lemmatizer = WordNetLemmatizer()self.spell = SpellChecker()self.wordnet_map = {"N": wordnet.NOUN, "V": wordnet.VERB, "J": wordnet.ADJ, "R": wordnet.ADV}def expand_contractions(self, text):expanded_text = contractions.fix(text)return expanded_textdef lemmatize_words(self, text):return " ".join([self.lemmatizer.lemmatize(word) for word in text.split()])def lemmatize_words_position(self, text):pos_tagged_text = nltk.pos_tag(text.split())return " ".join([self.lemmatizer.lemmatize(word, self.wordnet_map.get(pos[0], wordnet.NOUN)) for word, pos in pos_tagged_text])def remove_punctuation(self, text):"""custom function to remove the punctuation"""return text.translate(str.maketrans('', '', self.PUNCT_TO_REMOVE))def remove_space(self, text):return text.replace("_x000D_", " ")def remove_extra_space(self, text):return re.sub(' +', ' ', text)def remove_line_break_space(self, text):# return text.replace('\n', ' ').replace('\r', '')return " ".join([word for word in text.split()])def remove_html(self, text):return BeautifulSoup(text, features='html5lib').textdef lower_casing(self, text):return text.lower()def remove_urls(self, text):url_pattern = re.compile(r'https?://\S+|www\.\S+')return url_pattern.sub(r'', text)def remove_stopwords(self, text):"""custom function to remove the stopwords"""return " ".join([word for word in str(text).split() if word not in self.STOPWORDS])def stem_words(self, text):return " ".join([self.stemmer.stem(word) for word in text.split()])def remove_words(self, text, words):return " ".join([word for word in str(text).split() if word not in words])def correct_spellings(self, text):corrected_text = []misspelled_words = self.spell.unknown(text.split())for word in text.split():if word in misspelled_words:corrected_text.append(str(self.spell.correction(word)))else:corrected_text.append(str(word))if len(corrected_text) == 0:return  ""return " ".join(corrected_text)def replace_http_url(self, text,  word = "urladd"):return re.sub(r'https?://\S+|www\.\S+', word, text)def replace_email_id(self, text,  word = "emailadd"):return re.sub(r"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})", word,text)def replace_digit(self, text,  word = "digitadd"):return re.sub('\d+', word, text)if __name__ == '__main__':text_preprocessing = text_preprocessing()text ="""this text is for test"""text = text_preprocessing.replace_email_id(text)text = text_preprocessing.replace_http_url(text)text = text_preprocessing.replace_digit(text)text = text_preprocessing.expand_contractions(text)print(text)# text = text_preprocessing.remove_extra_space(text)# print('after removing extra space:', text)# old_text= text_preprocessing.remove_line_break_space(text)# print('old_text:',old_text)# text = text_preprocessing.lemmatize_words(old_text)# print("lemmatize_words_position:", text)# text = text_preprocessing.stem_words(old_text)# print("stem_words:",text)

Padas 处理的文字代码

import pandas as pd
from pandas import DataFrame
from tabulate import tabulate
from nlp.text_preprocessing_util.text_preprocessing import *base_dir = "C:/apps/ml_datasets"text_preprocessing = text_preprocessing()def get_dataset():data = pd.read_excel(base_dir+'/Support_email_category.xlsx', sheet_name='Emails')#data = pd.read_excel('../dataset/final.xlsx', sheetname='final')# data = data.apply(preprocess_data, axis=1)X_orig = data['Subject'].astype(str) +" "+  data['Email content']y_orig = data['Priority']new_data = pd.DataFrame()new_data['X_orig'] = X_orignew_data['y_orig'] = y_orignew_data.to_excel(base_dir+'/raw_data.xlsx', index=None)return new_datadef lower_casing(data: DataFrame):data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.lower_casing(text))return datadef remove_space(data: DataFrame):data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.remove_space(text))return datadef remove_punctuation(data: DataFrame):data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.remove_punctuation(text))return datadef remove_stopwords(data: DataFrame):data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.remove_stopwords(text))return datadef correct_spellings(data: DataFrame):data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.correct_spellings(text))return datadef remove_freqwords(data: DataFrame):from collections import Countercnt = Counter()for text in data["X_orig"].values:for word in text.split():cnt[word] += 1cnt.most_common(10)FREQWORDS = set([w for (w, wc) in cnt.most_common(10)])data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.remove_words(text, FREQWORDS))return datadef remove_rare_words(data: DataFrame):from collections import Countercnt = Counter()for text in data["X_orig"].values:for word in text.split():cnt[word] += 1cnt.most_common(10)n_rare_words = 10RAREWORDS = set([w for (w, wc) in cnt.most_common()[:-n_rare_words - 1:-1]])print("rarewords:", RAREWORDS)data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.remove_words(text, RAREWORDS))return datadef stem_words(data: DataFrame):data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.stem_words(text))return datadef lemmatize_words(data: DataFrame):data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.lemmatize_words(text))return datadef lemmatize_words1(data: DataFrame):import nltkfrom nltk.stem import WordNetLemmatizerfrom nltk.corpus import wordnetnltk.download('wordnet')lemmatizer = WordNetLemmatizer()wordnet_map = {"N": wordnet.NOUN, "V": wordnet.VERB, "J": wordnet.ADJ, "R": wordnet.ADV}data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.lemmatize_words_position(text, lemmatizer, wordnet_map))return datadef remove_urls(data: DataFrame):data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.remove_urls(text))return datadef remove_html(data: DataFrame):data["X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.remove_html(text))return datadef process_abbreviated_words(data: DataFrame):data["after X_orig"] = data["X_orig"].apply(lambda text: text_preprocessing.chat_words_conversion(text ))return datadef texts_preprocessing(data: DataFrame):data = remove_space(data)data = remove_urls(data)data= remove_html(data)data= process_abbreviated_words(data)data = lower_casing(data)# print(tabulate(data.head(3)))data = remove_punctuation(data)data = remove_stopwords(data)data= remove_freqwords(data)data = remove_rare_words(data)# data = stem_words(data)print('before...')print(tabulate(data.head(3)))# data = lemmatize_words(data)data = lemmatize_words1(data)# data = correct_spellings(data)print('after...')print(tabulate(data.head(3)))return datadef save_file(data, file_name):data.to_excel(base_dir + '/'+file_name, index=None)if __name__ == '__main__':data =  get_dataset()data = texts_preprocessing(data)save_file(data, 'after_preprocessing.xlsx')

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/213174.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【UML】NO.1 UML简介

目录 一、什么是UML 二、UML和软件工程 三、UML的诞生 四、UML的基本构成 从今天开始&#xff0c;开一个新的话题&#xff0c;把UML梳理一遍。 一、什么是UML UML&#xff08;Unified Modeling Language,UML&#xff09;是一个通用的可视化建模语言标准&#xff0c;用于对…

企业欠税信息API:实现税务管理的智能化与高效化

前言 随着经济的发展和社会的进步&#xff0c;企业欠税问题逐渐凸显&#xff0c;成为制约经济发展的重要因素。为了解决这一问题&#xff0c;企业欠税信息API应运而生。它通过先进的技术手段&#xff0c;提供了一种全新的欠税信息查询方式&#xff0c;帮助企业实现税务管理的智…

nginx多ip部署

1.修改网卡信息自定义多个IP 进入/etc/sysconfig/network-scripts&#xff0c;编辑ifcfg-ens33网卡文件。将dhcp动态分配修改成static&#xff0c;同时添加ip地址子网掩码、网关和DNS。 修改完成后重启网卡&#xff0c;systemctl restart network 2.修改nginx配置文件 有几个…

Vue3无废话,快速上手

Vue3无废话&#xff0c;快速上手 认识Vue3 1. Vue2 选项式 API vs Vue3 组合式API <script> export default {data(){return {count:0}},methods:{addCount(){this.count}} } </script><script setup> import { ref } from vue const count ref(0) const…

【c++随笔16】reserve之后,使用std::copy会崩溃?

【c随笔16】reserve之后&#xff0c;使用std::copy会崩溃? 一、reserve之后&#xff0c;使用std::copy会崩溃?二、函数std::reserve、std::resize、std::copy1、std::resize&#xff1a;2、std::reserve&#xff1a;3、std::copy&#xff1a; 三、崩溃原因分析方案1、你可以使…

机器学习 | Python贝叶斯超参数优化模型答疑

机器学习 | Python贝叶斯超参数优化模型答疑 目录 机器学习 | Python贝叶斯超参数优化模型答疑问题汇总问题1答疑问题2答疑问题3答疑问题汇总 问题1:想问一下贝叶斯优化是什么? 问题2:为什么使用贝叶斯优化? 问题3:如何实现? 问题1答疑 超参数优化在大多数机器学习流水线…

浅析不同NAND架构的差异与影响

SSD的存储介质是什么&#xff0c;它就是NAND闪存。那你知道NAND闪存是怎么工作的吗&#xff1f;其实&#xff0c;它就是由很多个晶体管组成的。这些晶体管里面存储着电荷&#xff0c;代表着我们的二进制数据&#xff0c;要么是“0”&#xff0c;要么是“1”。NAND闪存原理上是一…

安卓11修改power按键功能

客户需要把power键的短按休眠功能去除&#xff0c;并且把长按功能改成直接关机&#xff0c;我们先分析系统framework层处理按键的代码&#xff1a; interceptKeyBeforeQueueing power按键上来都会直接走这里&#xff0c;我们找到power按键处理的地方如下&#xff1a; case KeyE…

开启数据库性能之旅:MSSQL存储过程索引优化深度解析

数据库&#xff0c;如同一座庞大的图书馆&#xff0c;蕴藏着无数宝贵的信息。然而&#xff0c;想要在这个海量数据的世界中迅捷而准确地找到所需&#xff0c;索引就成为了至关重要的引路人。本文将引领读者深入探讨MSSQL存储过程中索引优化的奥妙&#xff0c;揭示数据库性能提升…

Spring日志完结篇,MyBatis操作数据库(入门)

目录 Spring可以对日志进行分目录打印 日志持久化&#xff08;让日志进行长期的保存&#xff09; MyBatis操作数据库(优秀的持久层框架) MyBatis的写法 开发规范&#xff1a; 单元测试的写法 传递参数 Spring可以对日志进行分目录打印 他的意思是说spring相关只打印INFO…

mysql中的DQL查询

表格为&#xff1a; DQL 基础查询 语法&#xff1a;select 查询列表 from 表名&#xff1a;&#xff08;查询的结果是一个虚拟表格&#xff09; -- 查询指定的列 SELECT NAME,birthday,phone FROM student -- 查询所有的列 * 所有的列&#xff0c; 查询结果是虚拟的表格&am…

中国各省、市乡村振兴水平数据(附stata计算代码,2000-2022)

数据简介&#xff1a;乡村振兴是当下经济学研究的热点之一&#xff0c;对乡村振兴进行测度&#xff0c;是研究基础。测度乡村振兴水平的学术论文广泛发表在《数量经济技术经济研究》等顶刊上。数据来源&#xff1a;主要来源于《中国农村统计年鉴》、《中国人口和就业统计年鉴》…

CRM系统选择技巧,什么样的CRM系统好用?

SaaS行业发展迅速&#xff0c;更多的企业逐渐选择CRM管理系统。打开搜索引擎&#xff0c;有非常多的结果。怎样在数十万个搜索结果中选择适合您的CRM系统&#xff1f;下面我们将聊聊&#xff0c;怎样选择CRM系统。 第一步&#xff1a;明确自身需求 重要性&#xff1a;每家企业…

仿照MyBatis手写一个持久层框架学习

首先数据准备&#xff0c;创建MySQL数据库mybatis&#xff0c;创建表并插入数据。 DROP TABLE IF EXISTS user_t; CREATE TABLE user_t ( id INT PRIMARY KEY, username VARCHAR ( 128 ) ); INSERT INTO user_t VALUES(1,Tom); INSERT INTO user_t VALUES(2,Jerry);JDBC API允…

深入理解Java虚拟机----内存区域的划分

Java虚拟机在执行Java程序的过程时&#xff0c;会将它管理的内存划分为若干个不同的数据区域。主要分为以下几个区域&#xff1a; 程序计数器 当前线程所执行的字节码的行号指示器。字节码解释器工作时通过改变程序计数器来选取下一条需要执行的字节码指令&#xff0c;分支、循…

nginx中Include使用

1.include介绍 自己的理解&#xff1a;如果学过C语言的话&#xff0c;感觉和C语言中的Include引入是一样的&#xff0c;引入的文件中可以写任何东西&#xff0c;比如server相关信息&#xff0c;相当于替换的作用&#xff0c;一般情况下server是写在nginx.conf配置文件中的&…

VR串流线方案:实现同时充电传输视频信号

VR&#xff08;Virtual Reality&#xff09;&#xff0c;俗称虚拟现实技术&#xff0c;是一项具有巨大潜力的技术创新&#xff0c;正在以惊人的速度改变我们的生活方式和体验&#xff0c;利用专门设计的设备&#xff0c;如头戴式显示器&#xff08;VR头盔&#xff09;、手柄、定…

idea 本身快捷键ctrl+d复制 无法像eclipse快捷键ctrl+alt+上下键,自动换行格式问题解决

问题 例如我使用ctrld 想复制如下内容 复制效果如下&#xff0c;没有自动换行&#xff0c;还需要自己在进行调整 解决 让如下快捷键第一个删除 修改成如下&#xff0c;将第二个添加ctrld 提示&#xff1a;对应想要修改的item&#xff0c;直接右键&#xff0c;remove是删…

分子生成领域的stable diffusion - GEOLDM

一、关于stable diffusion 很多人都知道stable diffusion&#xff0c;stable diffusion的出现改变了机器生成领域&#xff0c;让AI技术第一次无比的接近正常人。大语言模型&#xff0c;AIGC概念于是兴起。基于stable diffusion 大家开发了lora&#xff0c; hyperwork等微调技术…

[GWCTF 2019]我有一个数据库1

提示 信息收集phpmyadmin的版本漏洞 这里看起来不像是加密应该是编码错误 这里访问robots.txt 直接把phpinfo.php放出来了 这里能看到它所有的信息 这里并没有能找到可控点 用dirsearch扫了一遍 ####注意扫描buuctf的题需要控制扫描速度&#xff0c;每一秒只能扫10个多一个都…