|
|
import sqlite3 |
|
|
import pandas as pd |
|
|
import os |
|
|
from datetime import datetime |
|
|
import json |
|
|
|
|
|
def process_following_data(source_db_path, target_db_path, min_followers=20, max_followers=50): |
|
|
""" |
|
|
处理关注者数据,筛选出符合条件的用户并保存到新数据库 |
|
|
""" |
|
|
if not os.path.exists(source_db_path): |
|
|
raise FileNotFoundError(f"找不到数据库文件: {source_db_path}") |
|
|
|
|
|
conn = sqlite3.connect(source_db_path) |
|
|
|
|
|
print("正在读取关注关系数据...") |
|
|
df_relationships = pd.read_sql_query(""" |
|
|
SELECT user_id, following_of |
|
|
FROM following_relationships |
|
|
""", conn) |
|
|
|
|
|
print("正在统计关注者数量...") |
|
|
grouped = ( |
|
|
df_relationships |
|
|
.groupby('user_id')['following_of'] |
|
|
.agg(lambda x: list(set(x))) |
|
|
.reset_index() |
|
|
) |
|
|
grouped['follower_count'] = grouped['following_of'].apply(len) |
|
|
|
|
|
filtered = grouped[ |
|
|
(grouped['follower_count'] >= min_followers) & |
|
|
(grouped['follower_count'] <= max_followers) |
|
|
] |
|
|
|
|
|
print("正在获取用户详细信息...") |
|
|
target_users = tuple(filtered['user_id'].tolist()) |
|
|
|
|
|
if not target_users: |
|
|
print("没有找到符合条件的用户") |
|
|
conn.close() |
|
|
return 0 |
|
|
|
|
|
|
|
|
filtered['following_of'] = filtered['following_of'].apply(json.dumps) |
|
|
|
|
|
users_df = pd.read_sql_query(""" |
|
|
SELECT * |
|
|
FROM users |
|
|
WHERE user_id IN ({}) |
|
|
""".format(','.join(['?' for _ in target_users])), conn, params=target_users) |
|
|
|
|
|
|
|
|
result_df = pd.merge( |
|
|
users_df, |
|
|
filtered[['user_id', 'follower_count']], |
|
|
on='user_id', |
|
|
how='inner' |
|
|
) |
|
|
|
|
|
print(f"正在保存符合条件的 {len(result_df)} 个用户信息到新数据库...") |
|
|
|
|
|
|
|
|
target_conn = sqlite3.connect(target_db_path) |
|
|
|
|
|
|
|
|
if 'following_of' in result_df.columns: |
|
|
result_df = result_df.drop('following_of', axis=1) |
|
|
|
|
|
|
|
|
result_df.to_sql('users', target_conn, index=False, if_exists='replace') |
|
|
|
|
|
|
|
|
target_conn.execute("CREATE INDEX IF NOT EXISTS idx_user_id ON users(user_id)") |
|
|
target_conn.execute("CREATE INDEX IF NOT EXISTS idx_followers_count ON users(followers_count)") |
|
|
|
|
|
|
|
|
target_conn.execute(""" |
|
|
CREATE TABLE IF NOT EXISTS user_followers ( |
|
|
user_id TEXT PRIMARY KEY, |
|
|
followers TEXT, |
|
|
follower_count INTEGER, |
|
|
FOREIGN KEY(user_id) REFERENCES users(user_id) |
|
|
) |
|
|
""") |
|
|
|
|
|
|
|
|
followers_data = filtered[['user_id', 'following_of', 'follower_count']] |
|
|
followers_data.to_sql('user_followers', target_conn, index=False, if_exists='replace') |
|
|
|
|
|
|
|
|
print("\n符合条件的用户数据预览:") |
|
|
preview_df = result_df[['user_id', 'name', 'followers_count', 'friends_count']].head() |
|
|
print(preview_df) |
|
|
|
|
|
conn.close() |
|
|
target_conn.close() |
|
|
|
|
|
return len(result_df) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
source_db = "following_expanded.db" |
|
|
target_db = f"filtered_users_{datetime.now().strftime('%Y%m%d_%H%M%S')}.db" |
|
|
|
|
|
try: |
|
|
result_count = process_following_data(source_db, target_db) |
|
|
print(f"\n处理完成!已将 {result_count} 个用户的信息保存到 {target_db}") |
|
|
except Exception as e: |
|
|
print(f"处理过程中出现错误: {str(e)}") |
|
|
|
|
|
import traceback |
|
|
print("\n详细错误信息:") |
|
|
print(traceback.format_exc()) |