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

Python NYC街道树木数据统计程序故障排查与功能实现咨询

NYC街道树木统计程序故障排查与实现方案

故障排查核心要点

  • 文件路径验证:确保nyc_street_trees.csv和程序在同一目录,或者使用绝对路径(比如'C:/projects/nyc_street_trees.csv'),路径错误会导致程序读不到数据,自然无输出。
  • 列名匹配检查:CSV字段名必须和代码里的一致。可以取消代码中print("CSV列名:", reader.fieldnames)的注释,查看实际列名——比如有的数据集可能把树种列叫species而非spc_common,邮编列叫zip而非zipcode,列名不匹配会导致过滤不到数据。
  • 大小写统一处理:CSV里的树种名称可能是混合大小写(比如White Oak),用户输入可能是全小写或全大写,必须统一转成相同大小写(比如全小写)再匹配,否则会出现“有数据但匹配不到”的情况。
  • 空值过滤:CSV中可能存在缺失树种、邮编或行政区的行,这些行要提前过滤,避免统计出错。

完整可运行代码

import csv
from collections import Counter

def load_tree_data(file_path):
    tree_data = []
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            # 取消下面注释可查看CSV实际列名,用于验证匹配
            # print("CSV列名:", reader.fieldnames)
            for row in reader:
                # 过滤缺失关键字段的行
                if row.get('spc_common') and row.get('zipcode') and row.get('boroname'):
                    tree_data.append({
                        'species': row['spc_common'].strip().lower(),
                        'zipcode': row['zipcode'].strip(),
                        'borough': row['boroname'].strip()
                    })
        return tree_data
    except FileNotFoundError:
        print(f"错误:找不到文件 {file_path}")
        return []

def analyze_tree_species(tree_data, target_species):
    target_species = target_species.strip().lower()
    # 过滤出匹配的树种数据
    matches = [tree for tree in tree_data if tree['species'] == target_species]
    
    if not matches:
        return None
    
    total_count = len(matches)
    # 收集所有邮编并去重排序
    zipcodes = sorted(list({tree['zipcode'] for tree in matches}))
    # 统计各行政区的树木数量
    borough_counts = Counter(tree['borough'] for tree in matches)
    # 获取数量最多的行政区
    top_borough = borough_counts.most_common(1)[0]
    
    return {
        'total': total_count,
        'zipcodes': zipcodes,
        'top_borough': top_borough
    }

def main():
    tree_data = load_tree_data('nyc_street_trees.csv')
    if not tree_data:
        return
    
    while True:
        species_input = input("请输入树种名称(输入'q'退出):")
        if species_input.lower() == 'q':
            print("程序退出")
            break
        
        result = analyze_tree_species(tree_data, species_input)
        if not result:
            print(f"未找到树种 '{species_input}' 的数据\n")
            continue
        
        # 格式化输出统计结果
        print(f"\n树种 '{species_input}' 统计结果:")
        print(f"- 总数量:{result['total']}")
        print(f"- 所在邮编:{', '.join(result['zipcodes'])}")
        print(f"- 数量最多的行政区:{result['top_borough'][0]}({result['top_borough'][1]}棵)\n")

if __name__ == "__main__":
    main()

代码关键说明

  1. 数据加载:load_tree_data函数读取CSV,过滤无效行,统一树种名称为小写,解决大小写匹配问题。
  2. 统计逻辑:analyze_tree_species函数处理用户输入,过滤匹配数据,计算总数量、去重邮编,用Counter统计行政区数量并找出最多的那个。
  3. 交互逻辑:main函数循环接收用户输入,支持退出指令,无匹配数据时给出提示,有结果则格式化输出。

内容的提问来源于stack exchange,提问作者k.rob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:35:19