Texthero是一个可轻松处理文本数据集的python包。Texthero与pandas高度兼容,非常简单易学。给定一个以表格形式存储的文本数据集,仅需几行就能完成文本到向量的映射,帮助您快速处理文本。 Texthero包含用于以下目的的工具: ·预处理文本数据:它提供了即用型解决方案,但对于自定义解决方案也很灵活。·自然语言处理:关键短语和关键字提取,以及命名实体识别。·文本表示形式:TF-IDF,词频和自定义单词嵌入(WIP)·向量空间分析:聚类(K均值,Meanshift,DBSCAN和Hierarchical),主题建模(wip)和解释。·文本可视化:向量空间可视化,将本地化放置在地图上(WIP)。 Texthero是免费的,开源的并且有据可查的(这就是我们最喜欢的东西!)。 安装文末有本文代码文件夹获取方式,解压后请务必放置于电脑桌面。 在命令行切换到代码文件夹,然后依次执行下面的命令 #首先切换到代码文件夹 cd desktop/texthero学习 pip3 install gensim==3.8.1 pip3 install texthero==1.0.9 pip3 install en_core_web_sm-3.0.0-py3-none-any.whl 快速入门import pandas as pd import texthero as hero import warnings warnings.filterwarnings('ignore')
df = pd.read_csv("bbcsport.csv") df.head() 清洗数据texthero.clean(s: pd.Series, pipeline=None) 该函数操作的数据对象s是pd.Series类型的数据; pipeline管道参数可接受的函数有: ·fillna 剔除空值·lowercase 字母小写化·remove_digits 去除数字·remove_punctuatione 去除标点符号·remove_stopwords 去除停用词·remove_whitespace 去除空格等。 df['clean_text'] = hero.clean(df['text']) df.head() 定制管道pipelinefrom texthero import preprocessing
custom_pipeline = [preprocessing.fillna, preprocessing.remove_stopwords, preprocessing.lowercase, preprocessing.remove_whitespace]
df['clean_text'] = hero.clean(df['text'], custom_pipeline) df.head() 特征工程一旦清洗好数据后,就可以将每个文档(每行的文本)映射为一个向量 df['tfidf_clean_text'] = hero.tfidf(df['clean_text']) df.head() PCA降维要想在二维空间可视化多维数据,需要将df['tfidf_clean_text']进行pca主成分分析,达到降低维度的目的。 df['pca_tfidf_clean_text'] = hero.pca(df['tfidf_clean_text'], n_components=2) df.head() 一步到位上面的所有步骤(清洗文本、特征工程、pca降维),其实可以用一个代码块搞定。 df['pca'] = ( df['text'] .pipe(hero.clean) .pipe(hero.tfidf) .pipe(hero.pca, n_components=2) )
df.head() 可视化texthero.visualization对接pd.Series类型的数据,提供了可视化接口。 hero.scatterplot(df, col='pca', color='topic', title='PCA BBC Sport News') 总结上面的代码帮助我们发现有5个主题区域,而这一切,只用了短短的几行texthero代码。 import texthero as hero import pandas as pd
df = pd.read_csv("bbcsport.csv")
df['pca'] = ( df['text'] .pipe(hero.clean) .pipe(hero.tfidf) .pipe(hero.pca) )
hero.scatterplot(df, col='pca', color='topic', title="PCA BBC Sport news") 精选文章
|
|