文本預處理(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.pswp.cn/news/213174.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/213174.shtml
英文地址,請注明出處:http://en.pswp.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個多一個都…