![a07ca86d5c6876b56d9a9d87ad83dfea.png](https://i-blog.csdnimg.cn/blog_migrate/336f41506ac265b14d0c9ad2bb6c3d81.jpeg)
第一步:安装fasttext 可以参考:https://github.com/facebookresearch/fastText#building-fasttext
liunx版本下操作:
$ git clone https://github.com/facebookresearch/fastText.git
$ cd fastText
$ pip install .
安装成功后的导入:
新建test.py文件,写入:
import fastText.FastText as fasttext(可能会瞟红线)
新增:最近发现fasttext的github更新了,引入方式发生了变化,如果上述引入报错,改成 import fasttext.FastText as fasttext
新增:现在安装直接 pip install fasttext,导入直接 import fasttext 就行
保存后退出并运行:
python3 test.py
没报错说明安装成功
第二步:准备数据集
- 我这里用的是清华的新闻数据集(由于完整数据集较大,这里只取部分数据)
- 数据链接:点击获取网盘数据 提取码:
byoi
(data.txt为数据集,stopwords.txt为停用词) - 下载好后的数据格式为:
![45a3add553966ad06d7c24a5c9431d55.png](https://i-blog.csdnimg.cn/blog_migrate/0339022febec9029c1a4b0be728e247a.jpeg)
- 对应的标签分别为(由于只是用小部分数据,所以
data.txt
只包含部分标签):
mapper_tag = {
'财经': 'Finance',
'彩票': 'Lottery',
'房产': 'Property',
'股票': 'Shares',
'家居': 'Furnishing',
'教育': 'Education',
'科技': 'Technology',
'社会': 'Sociology',
'时尚': 'Fashion',
'时政': 'Affairs',
'体育': 'Sports',
'星座': 'Constellation',
'游戏': 'Game',
'娱乐': 'Entertainment'
}
第三步:数据预处理
- 由于
data.txt
已经经过了分词和去停用词的处理,所以这里只需要对数据进行切割为训练集和测试集即可。 - 分词和去停用词的工具代码(运行时不需要执行此部分代码):
import re
from types import MethodType, FunctionType
import jieba
def clean_txt(raw):
fil = re.compile(r"[^0-9a-zA-Zu4e00-u9fa5]+")
return fil.sub(' ', raw)
def seg(sentence, sw, apply=None):
if isinstance(apply, FunctionType) or isinstance(apply, MethodType):
sentence = apply(sentence)