How to use the pycountry.countries.get function in pycountry

To help you get started, we’ve selected a few pycountry examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github otherguy / alfred-airports-workflow / airports.py View on Github external
if airport_type != 'large_airport' and airport_type != 'small_airport' and airport_type != 'medium_airport': continue

            airport_type     = airport_type.split("_")[0]
            airport_name     = row['name'].strip()
            airport_coords   = { 'lat': float(row['latitude_deg']), 'lon': float(row['longitude_deg']) }
            airport_city     = row['municipality'].strip()
            airport_url      = row['home_link'].strip()
            airport_wiki     = row['wikipedia_link'].strip()
            airport_icao     = row['ident'].upper().strip()

            # Add a '.' after single uppercase letters
            airport_name = re.sub( r"\b([A-Z])(?![\w\-\.])", r"\1.", airport_name)

            country_iso_code = row['iso_country'].strip().upper()[:2]
            try :
                country = pycountry.countries.get(alpha_2=country_iso_code)
                country = country.name
            except (KeyError, AttributeError) as err:
                wf.logger.error("Error: {0} (Country: {1})".format(err, country_iso_code))
                country = country_iso_code

            airport_country = country

            # Build our airport object.
            airports.append( Map( id = airport_id, iata_code = iata_code, icao_code = airport_icao,
                type = airport_type, name = airport_name, coords = airport_coords,
                country = airport_country, city = airport_city, url = airport_url, wiki = airport_wiki ) )

        # Sort the list by airport_type. Snce it's only 'Large', 'Medium' and 'Small', they should be sorted correctly.
        airports = sorted(airports, key=lambda k: (k.type, k.iata_code))
        return airports
github mattduck / wbpy / wbpy / wbpy.py View on Github external
def _convert_to_alpha3(code):
    try:
        code = code.upper()
        if len(code) == 2:
            return pycountry.countries.get(alpha2=code).alpha3
        if len(code) == 3:
            return pycountry.countries.get(alpha3=code).alpha3
    except (KeyError, AttributeError):
        return code
github ushahidi / geograpy / geograpy / places.py View on Github external
if not self.regions:
            self.set_regions()

        if not self.db_has_data():
            self.populate_db()

        cur = self.conn.cursor()
        cur.execute("SELECT * FROM cities WHERE city_name IN (" + ",".join("?"*len(self.places)) + ")", self.places)
        rows = cur.fetchall()

        for row in rows:
            country = None
            
            try:
                country = pycountry.countries.get(alpha2=row[3])
                country_name = country.name
            except KeyError, e:
                country_name = row[4]

            city_name = row[7]
            region_name = row[6]

            if city_name not in self.cities:
                self.cities.append(city_name)

            if country_name not in self.countries:
                self.countries.append(country_name)
                self.country_mentions.append((country_name,1))

            if country_name not in self.country_cities:
                self.country_cities[country.name] = []
github mattduck / wbpy / wbpy / wbpy.py View on Github external
def _convert_to_alpha3(code):
    try:
        code = code.upper()
        if len(code) == 2:
            return pycountry.countries.get(alpha2=code).alpha3
        if len(code) == 3:
            return pycountry.countries.get(alpha3=code).alpha3
    except (KeyError, AttributeError):
        return code
github odoo-dominicana / l10n-dominicana / dgii_reports / models / dgii_report.py View on Github external
def _get_country_number(self, partner_id):
        """
        Returns ISO 3166 country number from partner
        country code
        """
        res = False
        if not partner_id.country_id:
            return False
        try:
            country = pycountry.countries.get(
                alpha_2=partner_id.country_id.code)
            res = country.numeric
        except AttributeError:
            return res
        return res
github Open-Power-System-Data / time_series / processing.py View on Github external
data_sets_singleindex = copy.deepcopy(data_sets)##########################
resources = []
for res_key, data_set in data_sets.items():
    columns_singleindex = [] ####################
    fields = [indexfield]
    for col in data_set.columns:
        h = {k: v for k, v in zip(HEADERS, col)}
        if len(h['country']) > 2:
            geo = h['country'] + ' control area'
        elif h['country'] == 'NI':
            geo = 'Northern Ireland'
        elif h['country'] == 'CS':
            geo = 'Serbia and Montenegro'
        else:
            geo = pycountry.countries.get(alpha2=h['country']).name

        field = {}    
        field['description'] = descriptions[h['attribute']].format(
            tech=h['variable'], geo=geo)
        field['type'] = 'number'
        field['source'] = {
            'name': h['source'],
            'web': h['web']
            }
        field['opsd-properties'] = {
            'Country': h['country'],
            'Variable': h['variable'],
            }
        components = [h['variable'], h['country']]
        if not h['variable'] == 'load':
            components.append(h['attribute'])
github mattduck / wbpy / wbpy / utils.py View on Github external
:param return_alpha:
        "alpha2" or "alpha3".

    """
    try:
        # Try to get code from ISO 1366 standard
        code = code.upper()
        country = None
        if len(code) == 2:
            try:
                country = pycountry.countries.get(alpha_2=code)
            except KeyError:
                country = pycountry.countries.get(alpha2=code)
        elif len(code) == 3:
            try:
                country = pycountry.countries.get(alpha_3=code)
            except KeyError:
                country = pycountry.countries.get(alpha3=code)
        else:
            raise ValueError("`code` is not a valid alpha-2 or alpha-3 code")
        if country is None:
            # Ugly way to get to the except branch below. Pycountry will raise
            # KeyError automatically in versions < 18.12.8
            raise KeyError
        try:
            return getattr(country, return_alpha)
        except AttributeError:
            if "_" not in return_alpha:
                return_alpha = return_alpha.replace("2", "_2").replace("3", "_3")
                return getattr(country, return_alpha)

    except (KeyError, ValueError):
github mdomke / schwifty / schwifty / bic.py View on Github external
def country(self):
        """Country: The country this BIC is registered in."""
        return countries.get(alpha_2=self.country_code)
github oasis-open / cti-stix-elevator / stix2elevator / convert_stix.py View on Github external
def determine_country_code(geo):
    if geo.name_code:
        return geo.name_code
    else:
        iso = pycountry.countries.get(name=geo.value)
        if iso:
            return iso.alpha_2
        else:
            if geo.value:
                warn("No ISO code for %s, therefore using full name", 618, geo.value)
                return geo.value
            else:
                return None
github alephdata / aleph / aleph / search / facets.py View on Github external
key = bucket.get('key_as_string', bucket.get('key'))
    data = {
        'count': bucket.get('doc_count'),
        'id': key,
        'label': key,
    }

    if facet == 'languages':
        try:
            locale = Locale(key.strip().lower())
            data['label'] = locale.get_display_name('en_US')
        except:
            pass
    elif facet == 'countries' and key is not None:
        try:
            country = countries.get(alpha2=key.strip().upper())
            data['label'] = country.name
        except:
            pass
    return data