python 特定于地理位置的国家/洲

jdg4fx2g  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(170)

给定经度和纬度,我想找到它所属的国家/大陆。另外,如果可能的话,还有其他特征,如该地区的海拔。这个question回答了,但不完全。

from geopy.geocoders import Nominatim
from pprint import pprint
geolocator = Nominatim()
location = geolocator.reverse("52.509669, 13.376294")
pprint(dir(location))
print(location.address)

   #No country/continent option
['__class__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__getattribute__',
 '__getitem__',
 '__hash__',
 '__init__',
 '__iter__',
 '__len__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__slots__',
 '__str__',
 '__subclasshook__',
 '__unicode__',
 '_address',
 '_point',
 '_raw',
 '_tuple',
 'address',
 'altitude',
 'latitude',
 'longitude',
 'point',
 'raw']
Potsdamer Platz, Mitte, Berlin, 10117, Deutschland
watbbzwu

watbbzwu1#

有点晚了:),但为了将来参考和那些可能需要它的人,像我最近,这里有一个方法来做维基百科和使用Pandasrequestsgeopy

import pandas as pd
import requests
from geopy.geocoders import Nominatim

URLS = {
    "Africa": "https://en.wikipedia.org/wiki/List_of_sovereign_states_and_dependent_territories_in_Africa",
    "Asia": "https://en.wikipedia.org/wiki/List_of_sovereign_states_and_dependent_territories_in_Asia",
    "Europe": "https://en.wikipedia.org/wiki/List_of_sovereign_states_and_dependent_territories_in_Europe",
    "North America": "https://en.wikipedia.org/wiki/List_of_sovereign_states_and_dependent_territories_in_North_America",
    "Ocenia": "https://en.wikipedia.org/wiki/List_of_sovereign_states_and_dependent_territories_in_Oceania",
    "South America": "https://en.wikipedia.org/wiki/List_of_sovereign_states_and_dependent_territories_in_South_America",
}
def get_continents_and_countries() -> dict[str, str]:
    """Helper function to get countries and corresponding continents.

    Returns:
        Dictionary where keys are countries and values are continents.

    """
    df_ = pd.concat(
        [
            pd.DataFrame(
                pd.read_html(
                    requests.get(url).text.replace("<br />", ";"),
                    match="Flag",
                )[0]
                .pipe(
                    lambda df_: df_.rename(
                        columns={col: i for i, col in enumerate(df_.columns)}
                    )
                )[2]
                .str.split(";;")
                .apply(lambda x: x[0])
            )
            .assign(continent=continent)
            .rename(columns={2: "country"})
            for continent, url in URLS.items()
        ]
    ).reset_index(drop=True)
    df_["country"] = (
        df_["country"]
        .str.replace("*", "", regex=False)
        .str.split("[")
        .apply(lambda x: x[0])
    ).str.replace("\xa0", "")
    return dict(df_.to_dict(orient="split")["data"])
def get_location_of(coo: str, data: dict[str, str]) -> tuple[str, str, str]:
    """Function to get the country of given coordinates.

    Args:
        coo: coordinates as string ("lat, lon").
        data: input dictionary of countries and continents.

    Returns:
        Tuple of coordinates, country and continent (or Unknown if country not found).

    """
    geolocator = Nominatim(user_agent="stackoverflow", timeout=25)
    country: str = (
        geolocator.reverse(coo, language="en-US").raw["display_name"].split(", ")[-1]
    )
    return (coo, country, data.get(country, "Unknown"))

最后:

continents_and_countries = get_continents_and_countries()

print(get_location_of("52.509669, 13.376294", continents_and_countries))

# Output
('52.509669, 13.376294', 'Germany', 'Europe')

相关问题