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为停用词)
下载好后的数据格式为:
对应的标签分别为(由于只是用小部分数据,所以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-Z\u4e00-\u9fa5]+")
return fil.sub(' ', raw)
def seg(sentence, sw, apply=None):
if isinstance(apply, FunctionType) or isinstance(apply, MethodType):
sentence = apply(sentence)
return ' '.join([i for i in jieba.cut(sentence) if i.strip() and i not in sw])
def stop_words():
with open('stop_words.txt', 'r', encoding='utf-8') as swf:
return [line.strip() for line in swf]
# 对某个sentence进行处理:
content = '上海天然橡胶期价周三再创年内新高,主力合约突破21000元/吨重要关口。