有关文本的一些流程总结

之前一段时间研究了文本相似度分析和文本分类,他们二者的大致前期流程还是有相似性的,我在这里做一个总结。

流程大致分为:

****读取数据****

读数据的过程中,就看大家的方便了,我在之前总结过excel的读取方式,在此次也同样用excel作为读入过程:

def getData():
    workbook = xlrd.open_workbook("路径\xxx.xlsx")
    sheet = workbook.sheet_by_name("sheet1")
    data = sheet.col_values(0)
    return  data
**数据处理:**

无论是word2vec 还是fasttext都要经历去停用词,分词的过程。这个过程就是为了后面的文本训练做准备的。

获取停用词字典:

#datapath是用来放获取路径的
def getStopWords(datapath):
    stopwords = pd.read_csv(datapath, index_col=False, quoting=3, sep="\t", names=['stopword'], encoding='utf-8')
    stopwords = stopwords["stopword"].values
    return stopwords

去掉停用词,对文本进行分词:

def preprocess_text(content, sentences, stopwords):
    for line in content:
            segs = jieba.lcut(line)  # 利用结巴分词进行中文分词
            segs = filter(lambda x: len(x) > 1, segs)  # 去掉长度小于1的词
            segs = filter(lambda x: x not in stopwords, segs)  # 去掉停用词
            sentences.append(segs)
**数据输出**:

之后有必要的话,可以将处理后的文本进行输出备份

word2vec:

def writeData(sentences, fileName):
    print("writing data to word2vec model ")
    out = open(fileName, 'w',encoding='utf-8')
    for sentence in sentences:
        sentence=list(sentence)
        out.write(' '.join(sentence))
        out.write("\n")
**模型训练:**

这个部分word2vec和fasttext稍微有些区别,在这里分别处理:

word2vec文本相似度:

def similar(text):
    target = "xxx.txt"  # 语料,这个输入的txt文件就是上面几步处理后输出的文本
    model = "w2v.mod"  # word2vec模型,可以在网上下载,也可以自己用更权威的语料自己做
    model_w2v = Word2Vec.load(model)
    candidates = []
    with open(target, encoding='utf-8')as f:
        for line in f:
            candidates.append(line.strip().split())  # 将语料放到列表中便于操作

    words = jieba.lcut(text.strip()) # 分词
    flag = False
    word = []
    for w in words:
        if w  in model_w2v.wv.vocab:
            word.append(w)

    # 文本匹配
    res = []
    index = 0
    for candidate in candidates:
        for c in candidate:
            if c not in model_w2v.wv.vocab:
                flag = True
        if flag:
            break
        score = model_w2v.n_similarity(word, candidate)

        resultInfo = {'id': index, "score": score, "text": " ".join(candidate)}
        res.append(resultInfo)
        index += 1
    res.sort(key=lambda x: x['score'], reverse=True)  # 进行排序

    # k = 0
    result = []  # 存放最终结果
    for i in range(len(res)):
        if res[i]['score'] > 0.75:  # 认为文本相似
            dict_temp = {res[i]['id']: res[i]['text'], "score": res[i]['score']}
            result.append(dict_temp)
    print(result)

fasttext文本分类:

import fastText.FastText as ft classifier = ft.train_supervised(saveDataFile)
    classifier.labels()
    # classifier = ft.supervised(saveDataFile, 'classifier.model', lable_prefix='__lable__')
    result = classifier.test(saveDataFile)
    print("P@1:", result.precision)  # 准确率
    print("R@2:", result.recall)  # 召回率
    print("Number of examples:", result.nexamples)  # 预测错的例子

fasttext过程其实和别的sklearn中的过程大同小异

以上就是我最近的总结。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值