File size: 3,827 Bytes
eb8ec0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import zstandard as zstd
import json
import csv
import os

def decompress_zst_file(zst_filename, output_filename):
    # 打开 .zst 文件并解压
    with open(zst_filename, 'rb') as zst_file:
        dctx = zstd.ZstdDecompressor()
        with open(output_filename, 'wb') as out_file:
            dctx.copy_stream(zst_file, out_file)

def extract_metadata_from_jsonl(jsonl_filename, csv_filename):
    # 打开 .jsonl 文件并解析其中的每行 JSON 数据
    with open(jsonl_filename, 'r') as jsonl_file:
        # 创建 CSV 文件来存储解析的数据
        with open(csv_filename, 'w', newline='', encoding='utf-8') as csv_file:
            csv_writer = csv.DictWriter(csv_file, fieldnames=['id', 'source', 'version', 'added', 'created', 'title', 'abstract', 'sha1', 'sources', 's2fieldsofstudy', 'extfieldsofstudy', 'external_ids'])
            csv_writer.writeheader()  # 写入表头
            
            for line in jsonl_file:
                try:
                    data = json.loads(line)  # 解析每一行的 JSON 数据
                    metadata = data.get('metadata', {})
                    
                    # 将 metadata 的值提取并写入 CSV 文件
                    csv_writer.writerow({
                        'id': data.get('id', ''),
                        'source': data.get('source', ''),
                        'version': data.get('version', ''),
                        'added': data.get('added', ''),
                        'created': data.get('created', ''),
                        'title': metadata.get('title', ''),
                        'abstract': metadata.get('abstract', ''),
                        'sha1': metadata.get('sha1', ''),
                        'sources': ', '.join(metadata.get('sources', [])),
                        's2fieldsofstudy': ', '.join(metadata.get('s2fieldsofstudy', [])),
                        'extfieldsofstudy': ', '.join(metadata.get('extfieldsofstudy', [])),
                        'external_ids': ', '.join([f"{eid['source']}:{eid['id']}" for eid in metadata.get('external_ids', [])])
                    })
                except json.JSONDecodeError:
                    print(f"Error decoding JSON in line: {line}")
                except Exception as e:
                    print(f"Error processing line: {line}, Error: {e}")

def process_zst_files(directory, output_directory):
    # 获取目录下所有 .zst 文件
    done_file = []
    for filename in os.listdir(directory):
        if filename.endswith('.zst') and filename not in done_file:
            zst_filepath = os.path.join(directory, filename)
            jsonl_filename = os.path.splitext(zst_filepath)[0] + '.jsonl'
            csv_filename = os.path.join(output_directory, os.path.splitext(filename)[0] + '.csv')
            
            # 解压 .zst 文件
            print(f"Decompressing {zst_filepath}...")
            decompress_zst_file(zst_filepath, jsonl_filename)
            
            # 提取 metadata 并保存到 CSV
            print(f"Extracting metadata from {jsonl_filename} and saving to {csv_filename}...")
            extract_metadata_from_jsonl(jsonl_filename, csv_filename)

            # 删除解压后的 .jsonl 文件(可选)
            os.remove(jsonl_filename)
            done_file.append(filename)
        print("done_file = ", done_file)

if __name__ == '__main__':
    # 设置您的 .zst 文件目录路径
    input_directory = 'my_data/peS2o_v3/data/v3'
    
    # 设置您想要保存 CSV 文件的输出目录路径
    output_directory = 'my_data/peS2o_v3/data/metadata'
    
    # 确保输出目录存在
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)
    
    # 处理目录中的所有 .zst 文件
    process_zst_files(input_directory, output_directory)