文本分类实战:基于哈工大停用词表和SVM算法的Python实现

本文将介绍如何使用Python实现文本分类,并提供一个使用SVM算法的示例代码。

准备工作

  1. 停用词表: 首先需要准备一个停用词表。你可以选择使用哈工大停用词表,下载地址为: http://ir.dlut.edu.cn/。
  2. 数据集: 我们将使用一个包含若干类数据的数据集,目录结构如下:
corpus
├── neg
│   ├── 1.txt
│   ├── 2.txt
│   └── ...
└── pos
    ├── 1.txt
    ├── 2.txt
    └── ...

代码实现

import os
import jieba
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.metrics import classification_report

# 加载停用词表
stopwords_path = 'stopwords.txt'
stopwords = set()
if os.path.exists(stopwords_path):
    with open(stopwords_path, 'r', encoding='utf-8') as f:
        for line in f:
            stopwords.add(line.strip())

# 加载语料库
corpus_dir = 'E:/Learning/大三下/自然语言处理/corpus'
corpus = []
labels = []
for label, dir_name in enumerate(['neg', 'pos']):
    dir_path = os.path.join(corpus_dir, dir_name)
    for file_name in os.listdir(dir_path):
        file_path = os.path.join(dir_path, file_name)
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read().strip()
            words = jieba.cut(content)
            words = [word for word in words if word not in stopwords]
            content = ' '.join(words)
            corpus.append(content)
            labels.append(label)

# 特征提取
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

# 分类器训练
clf = SVC()
clf.fit(X, labels)

# 测试集评估
test_corpus = [
    '这个电影真的很差劲,太失望了',
    '这部电影非常好看,特效也很棒',
]
test_labels = [0, 1]
test_X = vectorizer.transform(test_corpus)
pred_labels = clf.predict(test_X)
print(classification_report(test_labels, pred_labels))

代码说明

  1. 停用词处理: 代码首先加载停用词表,并使用jieba库对文本进行分词,去除停用词。
  2. 特征提取: 使用TfidfVectorizer类将文本转换为TF-IDF特征向量。
  3. SVM分类器训练: 使用SVC类训练SVM分类器。
  4. 测试集评估: 使用classification_report函数评估分类器的性能,输出精确率、召回率、F1值等指标。

总结

本文介绍了使用Python实现文本分类的步骤,并提供了一个使用SVM算法的示例代码。你可以根据自己的需求修改停用词表、特征提取方法和分类算法,以实现更优的文本分类效果。

文本分类实战:基于哈工大停用词表和SVM算法的Python实现

原文地址: https://www.cveoy.top/t/topic/ocXu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录