python爬取文本数据进行分类
时间: 2024-01-22 07:08:45 浏览: 81
要用Python进行文本分类,你需要先爬取一些文本数据,并对其进行预处理。一般来说,文本数据的预处理包括以下步骤:
1. 读取文本数据
2. 分词
3. 去除停用词
4. 提取特征
5. 训练模型
6. 对新数据进行分类
下面是一个简单的示例,演示如何用Python爬取文本数据并进行分类:
```python
import requests
from bs4 import BeautifulSoup
import jieba
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
# 网页爬取
url = "https://news.sina.com.cn/china/"
response = requests.get(url)
html = response.content.decode("utf-8")
soup = BeautifulSoup(html, "html.parser")
# 获取新闻标题
news_list = soup.find_all("a", href=True)
titles = []
for news in news_list:
title = news.text.strip()
if title:
titles.append(title)
# 分词和去除停用词
stop_words = ["的", "了", "和", "是"]
corpus = []
for title in titles:
words = jieba.cut(title)
words = [word for word in words if word not in stop_words]
corpus.append(" ".join(words))
# 特征提取和模型训练
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)
y = ["china"] * len(titles)
clf = MultinomialNB()
clf.fit(X, y)
# 预测新标题的类别
new_title = "新冠病毒疫苗开始接种"
new_words = jieba.cut(new_title)
new_words = [word for word in new_words if word not in stop_words]
new_corpus = [" ".join(new_words)]
new_X = vectorizer.transform(new_corpus)
predicted = clf.predict(new_X)
print(predicted[0])
```
在这个例子中,我们首先使用requests和BeautifulSoup库爬取了新浪网的中国新闻页面。然后我们对每个新闻标题进行了分词和去除停用词的处理。接着,我们使用TfidfVectorizer进行特征提取,并用MultinomialNB训练了一个朴素贝叶斯分类器。最后,我们使用这个分类器对一个新的标题进行了分类,输出了它属于“china”类别。
阅读全文
相关推荐


















