基本原理
將每個文本中的詞以逗號或者空格分開單獨作爲分類,在每個列表中統計詞出現的個數
只支持英文
作用
將文本內容轉化爲所需要的數據類型
類和方法
類
CountVectorizer(parm)
parm:max_df=x
返回詞頻矩陣
對文本進行特徵化
1.統計文章中的所有詞,重複的只看做一次 最後是詞的列表
2.對每篇文章,在詞的列表裏面進行統計每個詞出現的次數
注意:單個字母不統計
方法
方法 | 作用 |
---|---|
fit_transform(Param) | Param:字典或者包含字典的迭代器 返回值:返回sparse矩陣 |
inverse_transform(Param) | Parm:array數組或者sparse矩陣 返回值:轉換之前的數據格式 |
get_feature_names() | 返回值:返回分類類別的名稱 |
流程
data = [
'This is the first famous saying: Bao Jianfeng from sharpen out, plum blossom incense from the bitter cold',
'This is the second famous saying: learning is like rowing upstream; not to advance is to drop back',
'This is the third famous sentence: books have the road for the path, the sea of hard work',
]
def count_statistical():
"""
對文本進行特徵化
1.統計文章中的所有詞,重複的只看做一次 最後是詞的列表
2.對每篇文章,在詞的列表裏面進行統計每個詞出現的次數
注意:單個字母不統計
:return: None
"""
# 實例化
cs = CountVectorizer(max_df=1.0)
# 數據轉換
dat = cs.fit_transform(data)
# 打印單詞列表
print(cs.get_feature_names())
# 以矩陣樣式顯示
print(dat.toarray())
return None
中文文本處理
處理方法
利用jieba庫,先進行分詞處理,然後進行文本數據提取
流程
先分詞
from sklearn.feature_extraction.text import CountVectorizer
import jieba
def cutword():
# 分詞
sen1 = jieba.cut("這是第一句名言:寶劍鋒自磨出,梅花香自苦寒")
sen2 = jieba.cut("這是第二句名言:學習如逆水行舟;不進則退")
sen3 = jieba.cut("這是第三句名言:書山有路勤爲徑,學海無涯苦作舟")
# 轉化爲列表
sentence1 = list(sen1)
sentence2 = list(sen2)
sentence3 = list(sen3)
# 把列表轉換爲字符串
s1 = " ".join(sentence1)
s2 = " ".join(sentence2)
s3 = " ".join(sentence3)
return s1, s2, s3
特徵提取
def hanzi():
"""
中文特徵值化
:return: None
"""
s1, s2 , s3 = cutword()
print(s1, s2 , s3)
cv = CountVectorizer()
data = cv.fit_transform([s1, s2, s3])
# 打印分類
print(cv.get_feature_names())
# 轉化矩陣
print(data.toarray())