-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspider_origin.py
More file actions
261 lines (217 loc) · 8.82 KB
/
Copy pathspider_origin.py
File metadata and controls
261 lines (217 loc) · 8.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import sqlite3
import random
import time
import datetime
import requests
import joblib
import jieba
import os
from datetime import timedelta
# === 配置区域 ===
DB_NAME = 'database.db'
MODEL_PATH = 'models/sentiment_nb.pkl'
TARGET_KEYWORD = "厦门大学"
# === 1. 初始化数据库 (与原版保持一致) ===
def init_db():
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS posts
(
id
INTEGER
PRIMARY
KEY
AUTOINCREMENT,
content
TEXT
NOT
NULL,
source
TEXT,
sentiment_label
INTEGER,
publish_time
TIMESTAMP
)
''')
conn.commit()
conn.close()
# === 2. 加载模型 (用于辅助判断,如果模型不在,使用随机兜底) ===
model = None
try:
if os.path.exists(MODEL_PATH):
model = joblib.load(MODEL_PATH)
print("✅ 情感模型加载成功")
else:
print("⚠️ 未找到模型文件,将使用随机情感或规则判断")
except Exception:
pass
def predict_sentiment_safe(text, force_random=False):
"""
预测情感,如果模型不可用,则根据关键词规则或随机生成
返回: 1(积极), 0(中立), -1(消极)
"""
if model and not force_random:
try:
words = " ".join(jieba.cut(text))
return int(model.predict([words])[0])
except:
pass
# 简单的规则兜底 (Mock模式下很有用)
pos_keys = ['美', '喜欢', '爱', '棒', '绝', '好吃', '漂亮', '优秀', '开心', '推荐']
neg_keys = ['差', '烂', '讨厌', '烦', '贵', '难吃', '慢', '崩溃', '无语', '死']
score = 0
for k in pos_keys:
if k in text: score += 1
for k in neg_keys:
if k in text: score -= 1
if score > 0: return 1
if score < 0: return -1
return 0
# ==========================================
# 核心功能 A: 模拟数据生成器 (救急用)
# ==========================================
def generate_mock_data(count=50):
print(f"\n🧪 正在生成 {count} 条仿真数据...")
sources = ['微博', '微博', '微博', '百度贴吧', '百度贴吧', 'Bilibili']
# 语料库:针对厦门大学的特色语料
templates = [
# 积极
("厦大的{place}真的太美了,尤其是{time}的时候。", 1),
("必须吹爆{place}的{food},味道一绝!", 1),
("终于收到了厦大的录取通知书,{emotion}!", 1),
("表白{place}的保安大叔,人超级好。", 1),
("嘉庚建筑风格真的是独树一帜,最美校园名不虚传。", 1),
# 消极
("{place}的游客也太多了吧,根本没法{activity}。", -1),
("教务系统的选课服务器能不能升级一下?{emotion}。", -1),
("{place}的空调坏了三天了还没人修,热死了。", -1),
("避雷{place}的那个档口,又贵又难吃。", -1),
("学校周边的房租涨得太离谱了,{emotion}。", -1),
# 中立
("请问{place}怎么走?在线等。", 0),
("有同学出二手的{item}吗?价格好商量。", 0),
("关于{date}放假的通知出来了吗?", 0),
("求问这学期{course}是谁教的?", 0),
("刚刚在{place}看到一只流浪猫。", 0)
]
places = ['芙蓉隧道', '白城沙滩', '上弦场', '勤业餐厅', '图书馆', '翔安校区', '南光餐厅', '芙蓉湖']
foods = ['沙茶面', '手撕鸡', '老婆饼', '酸奶', '麻辣烫']
activities = ['自习', '跑步', '骑车', '吃饭', '散步']
emotions_pos = ['开心', '激动', '感动', '爱了爱了']
emotions_neg = ['崩溃', '无语', '烦躁', '心累']
items = ['自行车', '电磁炉', '教材', '雅思资料']
courses = ['高数', '大英', '毛概', 'C语言']
new_data = []
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
start_time = datetime.datetime.now() - timedelta(hours=48)
for _ in range(count):
tmpl, preset_label = random.choice(templates)
# 填词
text = tmpl.format(
place=random.choice(places),
time=random.choice(['傍晚', '清晨', '周末']),
food=random.choice(foods),
activity=random.choice(activities),
item=random.choice(items),
course=random.choice(courses),
date=random.choice(['国庆', '中秋', '寒假']),
emotion=random.choice(emotions_pos if preset_label == 1 else emotions_neg)
)
# 生成随机时间 (过去48小时内)
rand_minutes = random.randint(0, 48 * 60)
pub_time = start_time + timedelta(minutes=rand_minutes)
# 来源
src = random.choice(sources)
# 允许少量标签偏差,模拟真实世界的复杂性
final_label = preset_label
if random.random() < 0.1: # 10%概率预测错误或模糊
final_label = 0
c.execute('INSERT INTO posts (content, source, sentiment_label, publish_time) VALUES (?, ?, ?, ?)',
(text, src, final_label, pub_time))
new_data.append(text)
conn.commit()
conn.close()
print(f"✅ 成功生成并入库 {len(new_data)} 条数据!请刷新网页查看。")
# ==========================================
# 核心功能 B: 改进的爬虫 (需要Cookie才能稳定)
# ==========================================
def crawl_real_data():
print("\n🕷️ 启动真实爬虫模式...")
print("⚠️ 注意: 微博/贴吧现在反爬极严,如果不配置Cookie很难抓取。")
print("⚠️ 这里演示 Bilibili 的接口 (相对稳定)。")
# --- 1. Bilibili (API通常可用) ---
print(f" 正在抓取 Bilibili: {TARGET_KEYWORD} ...")
try:
url = "https://api.bilibili.com/x/web-interface/search/type"
params = {
'keyword': TARGET_KEYWORD,
'search_type': 'video',
'page': 1,
'order': 'pubdate' # 按时间排序
}
# 关键: B站现在需要更像浏览器的Header
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Referer": "https://www.bilibili.com/"
}
resp = requests.get(url, params=params, headers=headers, timeout=5)
data = resp.json()
count = 0
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
if data['code'] == 0:
items = data['data']['result']
for item in items:
title = item['title'].replace('<em class="keyword">', '').replace('</em>', '')
desc = item.get('description', '')
full_text = f"{title} {desc}"[:200]
# 情感分析
label = predict_sentiment_safe(full_text)
# 入库
c.execute('INSERT INTO posts (content, source, sentiment_label, publish_time) VALUES (?, ?, ?, ?)',
(full_text, 'Bilibili', label, datetime.datetime.now()))
count += 1
conn.commit()
print(f" ✅ Bilibili 抓取成功: {count} 条")
else:
print(" ❌ Bilibili 接口限制,未获取数据")
conn.close()
except Exception as e:
print(f" ❌ Bilibili 抓取出错: {e}")
# --- 2. 微博/贴吧 (提示用户) ---
print("\n💡 关于微博和贴吧:")
print(" 目前的脚本如果不带 Cookie (登录凭证) 几乎无法爬取这两个平台。")
print(" 建议直接使用【模拟数据模式】来填充数据库,效果一样好。")
# ==========================================
# 主程序入口
# ==========================================
if __name__ == '__main__':
init_db()
print("=" * 40)
print(" 厦门大学舆情系统 - 数据增强工具")
print("=" * 40)
print("1. 生成仿真数据 (推荐: 立即能看效果)")
print("2. 尝试真实爬取 (Bilibili可用,其他难)")
print("3. 清空数据库")
choice = input("\n请选择模式 (输入 1/2/3): ")
if choice == '1':
num = input("请输入生成数量 (默认50): ")
try:
n = int(num)
except:
n = 50
generate_mock_data(n)
elif choice == '2':
crawl_real_data()
elif choice == '3':
conn = sqlite3.connect(DB_NAME)
conn.execute("DELETE FROM posts")
conn.commit()
conn.close()
print("🗑️ 数据库已清空")
else:
print("无效选择")
print("\n🎉 操作完成! 现在请运行 app.py 启动网站。")