You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python/JavaScript读取NDJSON文件并分析人口年龄极值与均值

当然可以仅用Python或JavaScript实现这个需求。NDJSON本质是每行一个独立JSON对象的文本格式,非常适合逐行解析处理,哪怕是大文件也能高效处理,不需要一次性加载全部内容到内存。

Python实现方案

核心思路

  1. 逐行读取NDJSON文件,避免大文件内存溢出
  2. 解析每行的JSON对象,过滤出目标国家的记录
  3. 维护统计变量,实时更新最大年龄、最小年龄、总年龄和人数
  4. 最后计算平均年龄并输出结果

代码示例

import json

# 自定义配置
TARGET_COUNTRY = "China"
NDJSON_FILE = "population.ndjson"

# 初始化统计参数
max_age = -1
min_age = float('inf')
total_age = 0
person_count = 0

# 逐行处理文件
with open(NDJSON_FILE, 'r', encoding='utf-8') as file:
    for line_num, line in enumerate(file, 1):
        line = line.strip()
        if not line:
            continue
        try:
            person_data = json.loads(line)
            # 过滤目标国家的记录
            if person_data.get('country') == TARGET_COUNTRY:
                age = person_data.get('age')
                # 跳过缺失年龄的记录
                if age is None or not isinstance(age, (int, float)):
                    continue
                # 更新统计值
                if age > max_age:
                    max_age = age
                if age < min_age:
                    min_age = age
                total_age += age
                person_count += 1
        except json.JSONDecodeError:
            print(f"第 {line_num} 行无效,跳过: {line}")

# 计算并输出结果
average_age = total_age / person_count if person_count > 0 else 0
print(f"=== {TARGET_COUNTRY} 人口年龄统计 ===")
print(f"最年长年龄: {max_age if person_count > 0 else '无有效数据'}")
print(f"最年轻年龄: {min_age if person_count > 0 else '无有效数据'}")
print(f"平均年龄: {average_age:.2f}")
JavaScript(Node.js)实现方案

核心思路

  1. 使用Node.js的readline模块高效逐行读取文件
  2. 解析每行JSON,筛选目标国家的记录
  3. 实时更新统计变量,最后计算平均年龄

代码示例

const fs = require('fs');
const readline = require('readline');

// 自定义配置
const TARGET_COUNTRY = "China";
const NDJSON_FILE = "population.ndjson";

// 初始化统计参数
let maxAge = -1;
let minAge = Infinity;
let totalAge = 0;
let personCount = 0;

// 创建逐行读取流
const lineReader = readline.createInterface({
    input: fs.createReadStream(NDJSON_FILE, 'utf8'),
    crlfDelay: Infinity // 识别所有换行符
});

// 处理每一行数据
lineReader.on('line', (line) => {
    line = line.trim();
    if (!line) return;
    try {
        const personData = JSON.parse(line);
        if (personData.country === TARGET_COUNTRY) {
            const age = personData.age;
            // 跳过缺失或非数值的年龄
            if (age === undefined || age === null || typeof age !== 'number') {
                return;
            }
            // 更新统计值
            if (age > maxAge) maxAge = age;
            if (age < minAge) minAge = age;
            totalAge += age;
            personCount++;
        }
    } catch (error) {
        console.log(`无效JSON行,跳过: ${line}`);
    }
});

// 读取完成后输出结果
lineReader.on('close', () => {
    const averageAge = personCount > 0 ? (totalAge / personCount).toFixed(2) : 0;
    console.log(`=== ${TARGET_COUNTRY} 人口年龄统计 ===`);
    console.log(`最年长年龄: ${personCount > 0 ? maxAge : '无有效数据'}`);
    console.log(`最年轻年龄: ${personCount > 0 ? minAge : '无有效数据'}`);
    console.log(`平均年龄: ${averageAge}`);
});

注意:如果是浏览器环境,可通过File API读取用户上传的NDJSON文件,核心逻辑和上面一致,只是文件读取方式改为通过FileReader逐行处理。

内容的提问来源于stack exchange,提问作者Hamsu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 11:10:37