Datasets:

Modalities:
Text
Formats:
text
Size:
< 1K
Libraries:
Datasets
License:
File size: 3,812 Bytes
bc33227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)
    
    # 确保删除following_of列(如果存在),因为我们会在单独的表中存储它
    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())