函數說明:
1. re.sub(r'[^a-zA-Z0-9\s]', repl='', sting=string) 用於進行字符串的替換,這里我們用來去除標點符號
參數說明:r'[^a-zA-Z0-9\s]' 配對的模式,^表示起始位置,\s表示終止位置,[]表示取中間部分,這個的意思是找出除字符串大小寫或者數字組成以外的東西,repl表示使用什么進行替換,這里使用'',即直接替換,string表示輸入的字符串
2. stopwords = nltk.corpus.stopwords.words('english') # 表示獲得英文的停用詞表, 使用nltk.download下載停用詞表
3. nltk.WordPunctTokenizer() 構建模型,使用.tokenize(str) 對字符串進行分詞操作
4. np.vectorize(函數) 表示對函數進行向量化操作,使得對函數輸入的參數如果是列表形式,輸入的時候一個個輸入,輸出的時候也是一個個輸出
5.sklearn.extract_features.text.CountVectorizer 構建詞頻詞袋模型,.get_feature_names獲得詞袋模型的標簽
在一個文本數據輸入的時候,我們需要對其做數字編碼,一種就是根據文本出現的次數做一個詞袋模型
當一個文本數據輸入的時候
第一步:去除標點符號,並進行分詞操作(使用nltk.WordPunctTokenizer().tokenize進行分詞操作)
第二步:依據生成的停用詞表,去除停用詞,並且使用‘ ’.join進行串接,為了下一步的詞袋模型做准備
第三步:使用CountVectorizer, 對向量進行詞頻統計,將文本數據進行向量化操作,使用.get_feature_names()獲得詞袋中的詞語的名字
代碼:
第一步:構建DateFrame格式,同時數組化數據
第二步:載入停用詞表nltk.corpus.stopwords.words('english')和構建分詞nltk.WordPunctTokenize()模型,定義函數Normalize_corpus:使用re.sub去除標點符號, 使用.tokenize進行分詞,將分完成的列表,使用停用表去除停用詞,最后使用' '.join連接分詞后的列表為下一步構造詞袋模型做准備
第三步: 使用np.vectorize(Normalize_corpus) 對函數進行向量化操作,調用函數對列表進行分詞和去除停用詞的操作
第四步:使用sklearn.feature_extraction.text import CountVectorizer 構建詞頻的詞袋模型,使用.get_feature_names獲得詞袋模型的特征標簽
import pandas as pd import numpy as np import re import nltk #pip install nltk corpus = ['The sky is blue and beautiful.', 'Love this blue and beautiful sky!', 'The quick brown fox jumps over the lazy dog.', 'The brown fox is quick and the blue dog is lazy!', 'The sky is very blue and the sky is very beautiful today', 'The dog is lazy but the brown fox is quick!' ] labels = ['weather', 'weather', 'animals', 'animals', 'weather', 'animals'] # 第一步:構建DataFrame格式數據 corpus = np.array(corpus) corpus_df = pd.DataFrame({'Document': corpus, 'categoray': labels}) # 第二步:構建函數進行分詞和停用詞的去除 # 載入英文的停用詞表 stopwords = nltk.corpus.stopwords.words('english') # 建立詞分割模型 cut_model = nltk.WordPunctTokenizer() # 定義分詞和停用詞去除的函數 def Normalize_corpus(doc):
# 可以使用re.findall(r'[a-zA-Z0-9]+', doc.lower()) 直接去除標點符號和進行分詞構造詞列表 # 去除字符串中結尾的標點符號 doc = re.sub(r'[^a-zA-Z0-9\s]', '', string=doc) # 是字符串變小寫格式 doc = doc.lower() # 去除字符串兩邊的空格 doc = doc.strip() # 進行分詞操作 tokens = cut_model.tokenize(doc) # 使用停止用詞表去除停用詞 doc = [token for token in tokens if token not in stopwords] # 將去除停用詞后的字符串使用' '連接,為了接下來的詞袋模型做准備 doc = ' '.join(doc) return doc # 第三步:向量化函數和調用函數 # 向量化函數,當輸入一個列表時,列表里的數將被一個一個輸入,最后返回也是一個個列表的輸出
# norm_corpus = corpus_df['Document'].apply(Normalize_vector) 也可以使用DateFrame格式中的apply進行應用
Normalize_corpus = np.vectorize(Normalize_corpus) # 調用函數進行分詞和去除停用詞 corpus_norm = Normalize_corpus(corpus) # 第四步:使用CountVectorizer做詞頻的詞袋模型 from sklearn.feature_extraction.text import CountVectorizer Cv = CountVectorizer() Cv.fit(corpus_norm) # 使用.get_feature_names()獲得詞袋模型的特征標簽 corpus_names = Cv.get_feature_names() corpus_array = Cv.transform(corpus_norm).toarray() corpus_df = pd.DataFrame(corpus_array, columns=corpus_names) print(corpus_df.head())