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

如何使用Python的pycountry库获取指定国家的州与城市列表?

关于用Python获取指定国家的州和城市列表的问题

pycountry的局限性

pycountry库仅提供国家层面的标准化数据(如国家名称、ISO 3166代码等),不包含州/省、城市这类细分行政区域的信息,所以仅靠pycountry无法实现你要的功能。

可行解决方案:使用专门的地理数据库

可以使用countries-states-cities-db这类专注于行政区域数据的第三方库,它包含全球大多数国家的州、城市层级数据。

步骤1:安装库

pip install countries-states-cities-db

步骤2:编写Django视图示例

下面是适配你现有代码风格的视图,支持通过请求参数指定国家(ISO代码或名称均可),返回对应的州和城市列表:

from django.http import JsonResponse
import status
from countries_states_cities_db import Database

def get_country_regions(request):
    # 获取请求参数中的国家标识
    country_identifier = request.GET.get('country')
    if not country_identifier:
        return JsonResponse(
            {"code": status.HTTP_400_BAD_REQUEST, "success": False, "response": "请提供国家标识(ISO代码或名称)"},
            status=status.HTTP_400_BAD_REQUEST
        )
    
    db = Database()
    try:
        # 优先通过ISO代码查找国家,找不到则尝试名称匹配
        country = db.get_country_by_iso(country_identifier) or db.get_country_by_name(country_identifier)
        if not country:
            return JsonResponse(
                {"code": status.HTTP_404_NOT_FOUND, "success": False, "response": "未找到指定国家"},
                status=status.HTTP_404_NOT_FOUND
            )
        
        # 获取该国家的所有州/省、城市
        states = db.get_states_of_country(country['id'])
        cities = db.get_cities_of_country(country['id'])
        
        # 整理返回数据
        response_data = {
            "code": status.HTTP_200_OK,
            "success": True,
            "country": country['name'],
            "states": [state['name'] for state in states],
            "cities": [city['name'] for city in cities]
        }
        return JsonResponse(response_data, status=status.HTTP_200_OK)
    except Exception as e:
        return JsonResponse(
            {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "success": False, "response": str(e)},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

# 修正你现有获取国家列表的代码(避免使用内置变量名list)
def Countries(request):
    country_list = []
    for country in pycountry.countries:
        country_list.append(country.name)
    if country_list:
        return JsonResponse(
            {"code": status.HTTP_200_OK, "success": True, "response": country_list},
            status=status.HTTP_200_OK
        )
    else:
        return JsonResponse(
            {"code": status.HTTP_400_BAD_REQUEST, "success": False, "response": "国家列表为空"},
            status=status.HTTP_400_BAD_REQUEST
        )

额外说明

  • 可通过请求/get_country_regions?country=CN(中国ISO代码)或/get_country_regions?country=China获取对应数据
  • 若需要按州过滤城市,可调用db.get_cities_of_state(state_id)方法实现

内容的提问来源于stack exchange,提问作者Aashu kumar jha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:21:39