def get_country_details(self, country): """Returns country code(alpha_3) and continent""" try: country_obj = pycountry.countries.get(name=country) if country_obj is None: c = pycountry.countries.search_fuzzy(country) country_obj = c[0] continent_code = pc.country_alpha2_to_continent_code( country_obj.alpha_2) continent = pc.convert_continent_code_to_continent_name( continent_code) return country_obj.alpha_3, continent except: if 'Congo' in country: country = 'Congo' if country == 'Mainland China': country = 'China' elif country == 'Diamond Princess' or country == 'Laos' or country == 'MS Zaandam' or country == 'Holy See' or country == 'Timor-Leste': return country, country elif country == 'Korea, South' or country == 'South Korea': country = 'Korea, Republic of' elif country == 'Taiwan*': country = 'Taiwan' elif country == 'Burma': country = 'Myanmar' elif country == 'West Bank and Gaza': country = 'Gaza' else: return country, country country_obj = pycountry.countries.search_fuzzy(country) continent_code = pc.country_alpha2_to_continent_code( country_obj[0].alpha_2) continent = pc.convert_continent_code_to_continent_name( continent_code) return country_obj[0].alpha_3, continent
def reverse_geocode(lat, lng): reverse_data = geocoder.osm_reverse.OsmReverse((lat, lng)).geojson country = None city = None continent = None try: feature_properties = reverse_data['features'][0]['properties'] cc = feature_properties['country_code'].upper() city = None if "city" in feature_properties: city = feature_properties['city'] elif "town" in feature_properties: city = feature_properties["town"] elif "state" in feature_properties: city = feature_properties['state'] elif "county" in feature_properties: city = feature_properties['county'] country = pycountry.countries.get(alpha_2=cc).name continent_code = country_alpha2_to_continent_code(cc) continent = convert_continent_code_to_continent_name(continent_code) except: return None, None, None else: return continent, country, city
def add_continent_name(self) -> None: """ Adds a continent name to this tweet. """ if self.has_continent_name(): # already has a continent name return if self.country_code is None or len(self.country_code) != 2: # incorrect country code self.continent: None = None return if self.country_code == 'AQ': # special case self.continent: str = 'Antarctica' return try: # return continent name from country code self.continent: str = convert_continent_code_to_continent_name( country_alpha2_to_continent_code(self.country_code)) return except: # return None if this fails self.continent: None = None return
def f(update, context): correct_country = context.bot_data['correct_country'] if selected_country == correct_country.alpha_2: txt = "{} - {}".format(correct_country.name, np.random.choice(positive_feedback, 1)[0]) else: txt = "{} - {} Richtig wäre gewesen:\n{} ({}), {}".format( selected_country, np.random.choice(negative_feedback, 1)[0], correct_country.name, correct_country.alpha_2, pc.convert_continent_code_to_continent_name( country_alpha2_to_continent_code(correct_country.alpha_2))) # store user_id = update.callback_query.message.chat.id country_id = correct_country.alpha_2 answer_country_id = selected_country data = database.insert_answer(user_id=user_id, country_id=country_id, answer_country_id=answer_country_id) logger.info("Created data point") logger.info(data) update.callback_query.edit_message_text( txt, reply_markup=InlineKeyboardMarkup([[]])) time.sleep(1) start(update, context)
def country_to_continent(country_name): country_alpha2 = pc.country_name_to_country_alpha2(country_name) country_continent_code = pc.country_alpha2_to_continent_code( country_alpha2) country_continent_name = pc.convert_continent_code_to_continent_name( country_continent_code) return country_continent_name
def addContinent(self, df): df['Continent'] = df.apply( lambda row: pc.convert_continent_code_to_continent_name( pc.country_alpha2_to_continent_code( pc.country_name_to_country_alpha2( row.country, cn_name_format="default"))), axis=1)
def country_to_continent(): country_name = input("country name = ") country_alpha2 = pc.country_name_to_country_alpha2(country_name) country_continent_code = pc.country_alpha2_to_continent_code( country_alpha2) country_continent_name = pc.convert_continent_code_to_continent_name( country_continent_code) print(country_continent_name)
def country_to_continent(country_name): "Convert country name string to continent" country_alpha2 = pcc.country_name_to_country_alpha2(country_name) country_continent_code = pcc.country_alpha2_to_continent_code( country_alpha2) country_continent_name = pcc.convert_continent_code_to_continent_name( country_continent_code) return country_continent_name
def get_continent(country_code): if country_code =='VA': return 'Europe' if country_code =='TL': return 'Asia' else: continent_name = pc.country_alpha2_to_continent_code(country_code) country_continent_name = pc.convert_continent_code_to_continent_name(continent_name) return country_continent_name
def convert_country_to_continent(country_alpha2: str): country_continent_name: str = "" try: country_continent_code: str = pc.country_alpha2_to_continent_code( country_alpha2) country_continent_name: str = pc.convert_continent_code_to_continent_name( country_continent_code) except Exception as e: logger.error(e) return country_continent_name
def country_to_continent(country_name): country_continent_name = "" try: country_alpha2 = pc.country_name_to_country_alpha2(country_name) country_continent_code = pc.country_alpha2_to_continent_code(country_alpha2) country_continent_name = pc.convert_continent_code_to_continent_name(country_continent_code) except: pass return country_continent_name
def country_code_to_continent(self, country_iso2_code=None): """ Returns continent name based on country ISO2 code since api used for ip-info did not return continent info. :param country_iso2_code: str :return: str """ if country_iso2_code: country_continent_code = pc.country_alpha2_to_continent_code(country_iso2_code) return pc.convert_continent_code_to_continent_name(country_continent_code) else: return None
def country_to_continent(country_name): try: if country_name == 'DR Congo': country_continent_name = 'Africa' else: fuzzy = pycountry.countries.search_fuzzy(country_name) country_alpha2 = pc.country_name_to_country_alpha2(fuzzy[0].name) country_continent_code = pc.country_alpha2_to_continent_code( country_alpha2) country_continent_name = pc.convert_continent_code_to_continent_name( country_continent_code) except: country_continent_name = 'Europe' return country_continent_name
def get_continent(country_name): try: country_code3 = cc.convert( country_name ) # convert country name to country code ISO 3 (3 letter code) country_code2 = coco.convert( names=country_code3, to='ISO2') # convert 3 letter code to 2 letter code country_continent_code = pc.country_alpha2_to_continent_code( country_code2) country_continent_name = pc.convert_continent_code_to_continent_name( country_continent_code) return country_continent_name except: return 'not found'
def get_continent_name(item): try: country_code = pc.country_name_to_country_alpha2( item, cn_name_format="default") continent_code = pc.country_alpha2_to_continent_code(country_code) continent_name = pc.convert_continent_code_to_continent_name( continent_code) return continent_name except KeyError: cont = get_key_val( countries, item, "continent" ) #Otherwise uses the method above if cannot find continent name in the library if cont != "Other": return cont else: return 'International'
def country_to_continent(country_name): """ Cette fonction permet de retrouver le continent en fonction du pays renseigné country_name = "France" country_continent_name retourne "Europe" This function allows you to find the continent according to the country you have entered country_name = "France country_continent_name returns "Europe". """ country_alpha2 = pc.country_name_to_country_alpha2(country_name) country_continent_code = pc.country_alpha2_to_continent_code( country_alpha2) country_continent_name = pc.convert_continent_code_to_continent_name( country_continent_code) return country_continent_name
def select_continent(update, context, replace=True): button_list = [] for code in continents(): label = "{}".format(pc.convert_continent_code_to_continent_name(code)) button_list.append( InlineKeyboardButton(label, callback_data="continent_{}".format(code))) reply_markup = InlineKeyboardMarkup(build_menu( button_list, n_cols=2)) #n_cols = 1 is for single column and mutliple rows bot = update.message if update.message else update.callback_query.message if not replace: bot.reply_text(text='Welcher Kontinent?', reply_markup=reply_markup) else: update.callback_query.edit_message_text(text='Welcher Kontinent?', reply_markup=reply_markup)
def get_non_working_days(self, year=None): """ Return non working days of current year Args: year (int): get non working day for specified year. If not specified use current year Returns: list: list of non working days of the year. List can be empty if error occured:: [ { datetime (string): non working day (date in iso format YYYY-MM-DD) label (string): english name of non working day }, ... ] """ self._check_parameters([{ "name": "year", "type": int, "value": year, "none": True, }]) try: country = self._get_config_field("country") continent_code = country_alpha2_to_continent_code( country["alpha2"]) continent_name = convert_continent_code_to_continent_name( continent_code).lower() continent_name = (continent_name.lower().replace( "south", "").replace("north", "").strip()) workalendar = importlib.import_module( f"workalendar.{continent_name}") fixed_country = "".join( [part.capitalize() for part in country["country"].split()]) _class = getattr(workalendar, fixed_country) _instance = _class() year = year or datetime.datetime.now().year holidays = _instance.holidays(year) return [(date.isoformat(), label) for (date, label) in holidays] except Exception: self.logger.exception("Unable to get non working days:") return []
def country_to_continent(country, verbose=False): if verbose: print(f'Processing country: {country}') try: country_obj = pycountry.countries.search_fuzzy(country)[0] except (LookupError, AttributeError) as e: print(f'Failed to process {country} due to error: {e}') return 'Unknown' try: continent_code = pycountry_convert.country_alpha2_to_continent_code( country_obj.alpha_2) except KeyError as e: print(f'Failed to process {country} due to error: {e}') return 'Unknown' continent = pycountry_convert.convert_continent_code_to_continent_name( continent_code) return continent
def check_new_country(self, conn): countries = self.get_all_countries(conn) try: countries_api = requests.get( "https://corona.lmao.ninja/v2/countries").json() except json.decoder.JSONDecodeError: #To prevent crashing of bot.py in case of Error 502 of corona.lmao.ninja pass else: for i in range(len(countries_api)): if countries_api[i]["country"] not in countries: try: continent = pycountry_convert.convert_continent_code_to_continent_name( pycountry_convert.country_alpha2_to_continent_code( countries_api[i]["countryInfo"]["iso2"])) statement = self.country.insert().values( country_name=countries_api[i]["country"], country_continent=continent).prefix_with('IGNORE') conn.execute(statement) except: pass return self.get_all_countries(conn)
def appendContinentCol(self): """ Maps countries to continents Parameters: self (dataframe): survey data with requested column names Returns: self (dataframe): survey data with requested column names and continent """ continent = [] for country in self['Q1. What is your country of residence?']: country_alpha2 = pc.country_name_to_country_alpha2(country) continent_alpha2 = pc.country_alpha2_to_continent_code(country_alpha2) continent.append( pc.convert_continent_code_to_continent_name(continent_alpha2)) col_idx = self.columns.get_loc( 'Q1. What is your country of residence?') + 1 self.insert(loc=col_idx, column='Q1. Continent', value=continent) return self
def initialize_countries(cursor): """Fetches country data (name, continent, cases, deaths, recovered, tests) from the API. Args: cursor (:obj:`mysql.connector.cursor.MySQLCursor`): Database cursor """ countries = get(cursor, "name", "country") try: data = jobs.fetch_data() except json.decoder.JSONDecodeError: # To prevent crashing of bot.py in case of Error 502 of corona.lmao.ninja pass else: for i in range(len(data)): if data[i]["country"] not in countries: try: continent = ( pycountry_convert.convert_continent_code_to_continent_name( pycountry_convert.country_alpha2_to_continent_code( data[i]["countryInfo"]["iso2"] ) ) ) cursor.execute( "INSERT IGNORE INTO country(name, continent, cases, deaths, recovered, tests) " "VALUES (%s, %s, %s, %s, %s, %s)", ( data[i]["country"], continent, data[i]["cases"], data[i]["deaths"], data[i]["recovered"], data[i]["tests"], ), ) except: pass
def get_continents(country): country = country.strip() continent = 'None' cruises = ['Diamond Princess', 'MS Zaandam'] africa = ['Congo (Brazzaville)', 'Congo (Kinshasa)', 'Cote d\'Ivoire', 'Western Sahara'] asia = ['Afghanistan', 'Korea, South', 'Taiwan*', 'Timor-Leste', 'West Bank and Gaza', 'Burma', 'Summer Olympics 2020', 'Winter Olympics 2022'] europe = ['Holy See', 'Kosovo'] north_america = ['US'] antarctica = ['Antarctica'] if country in africa: continent = 'AF' elif country in cruises: continent = 'Cruise' elif country in europe: continent = 'EU' elif country in asia: continent = 'AS' elif country in north_america: continent = 'NA' elif country in antarctica: continent = 'Antarctica' else: continent = pc.country_alpha2_to_continent_code( pc.country_name_to_country_alpha2(country, cn_name_format="default")) if continent not in ('Cruise','Antarctica'): continent = pc.convert_continent_code_to_continent_name(continent) return continent
except: print("Error reading data") data_frame2 = data_frame[['Country', 'ConvertedComp']].copy() data_frame2['Hobbyist'] = data_frame[['Hobbyist']].copy() data_frame2['Gender'] = data_frame[['Gender']].copy() data_frame2['CareerSat'] = data_frame[['CareerSat']].copy() data_frame2['JobSat'] = data_frame[['JobSat']].copy() data_frame2['Continent'] = None count = 0 for row in data_frame2['Country']: try: country_code = pc.country_name_to_country_alpha2( row, cn_name_format="default") continent_name = pc.country_alpha2_to_continent_code(country_code) country_continent_name = pc.convert_continent_code_to_continent_name( continent_name) data_frame2['Continent'][count] = country_continent_name count += 1 except: pass #Below code can be used for manually checking results of each function '''while True: print("\n\n\nSelect options from below to view report:\n"\ "\n1. Average age of developers when they wrote their first line of code\n"\ "2. Percentage of developers who know python in each country\n"\ "3. Average salary of developer based on continent\n"\ "4. Most desired programming language for the year 2020\n"\ "5. Distribution of people who code as a hobby based on gender and continent\n"\ "6. Report for job and career satisfaction of developer based on their gender and continent\n"\ "7. Exit\n")
#zad. 4 #Zainstaluj bibliotekę pycountry_convert i zaimportuj ją. #Dodaj do danych kolumnę continent, która będzie zawierać nazwę kontynentu, #na którym jest położone dane państwo. Wykorzystaj bibliotekę pycountry_convert. #Uwaga: trzeba najpierw uzystać kod państwa w fomacie ISO-2, następnie uzystkać kod kontynentu, a na końcu uzyskać nazwę kontynentu. import pycountry_convert conts = [] for name in data.index: country_code = pycountry_convert.convert_countries.country_name_to_country_alpha2( name) cont_code = pycountry_convert.convert_country_alpha2_to_continent_code.country_alpha2_to_continent_code( country_code) cont = pycountry_convert.convert_continent_code_to_continent_name( cont_code) conts.append(cont) data['continent'] = conts data['continent'] #zad. 5 Oblicz ile osób mieszka na każdym z kontynentów. data.groupby('continent').sum().population #zad. 6 Narysyj wykres słupkowy pokazujący ile państw leży na każdym z kontynentów. data.continent.value_counts().plot('bar') # zad. 7 #Kolumna gdp zawiera informacje o PKB na obywatela. Stwórz nową kolumnę gdp_total, która będzie informować o PKB danego kraju. #Oblicz ile wynosi suma światowego PKB (kolumna gdp_total).
def parse_meta(instring): """ 1: Pathogen: environmental/food/other sample from Salmonella enterica Identifiers: BioSample: SAMN10440521; Sample name: FSIS21822761; SRA: SRS4056931 Organism: Salmonella enterica Attributes: /strain="FSIS21822761" /collected by="USDA-FSIS" /collection date="2018" /geographic location="USA:WV" /isolation source="chicken carcass" /latitude and longitude="missing" /serovar="Typhimurium" /subgroup="enterica" """ # print(instring) outd = {} inlines = instring.splitlines() for line in inlines: if "collected by=" in line: outd["NCBI_submitted"] = line.strip(" ").replace( '/collected by="', "").replace('"', "") elif "collection date" in line: init_date = line.strip(" ").replace('/collection date="', "").replace('"', "") try: parsed = dateparse(init_date, default=DEFAULT) if len( init_date ) < 5: # if only year then will be 2 or 4 chars i.e. 18 or 2018 outd["collection_date"] = "" outd["collection_year"] = init_date elif len( init_date ) < 8: # if only year month will be 4,5 or 7 chars 9/18 or 09/18 or 09/2018 outd["collection_date"] = parsed.strftime('') outd["collection_year"] = parsed.strftime('%Y') else: outd["collection_date"] = parsed.strftime('%d/%m/%Y') outd["collection_year"] = parsed.strftime('%Y') except: outd["collection_date"] = "" outd["collection_year"] = "" elif "geographic location=" in line: inf = line.strip(" ").replace('/geographic location="', "").replace('"', "") outd["postcode"] = "" locinfo = inf.split(":") country = locinfo[0] outd["country"] = country if len(locinfo) > 1: outd["state"] = locinfo[1] if outd["country"].strip(" ") == outd["state"].strip(" "): outd["state"] = "" if country == "USA": country = "US" continent = pycountry_convert.country_alpha2_to_continent_code( country) else: try: country_2_alpha2 = dict( pycountry_convert.map_country_name_to_country_alpha2()) alpha2 = country_2_alpha2[country] continent = pycountry_convert.country_alpha2_to_continent_code( alpha2) except: continent = "" if continent != "": continent = pycountry_convert.convert_continent_code_to_continent_name( continent) outd["continent"] = continent elif "isolation source" in line: outd["isolation_source"] = line.strip(" ").replace( '/isolation source="', "").replace('"', "") elif "host=" in line: outd["isolation_source"] = line.strip(" ").replace('/host="', "").replace( '"', "") elif "isolate=" in line: outd["original_id"] = line.strip(" ").replace('/isolate="', "").replace('"', "") elif "strain=" in line: if "original_id" not in outd: outd["original_id"] = line.strip(" ").replace('/strain="', "").replace( '"', "") elif "Identifiers:" in line: inf = line.replace("Identifiers: ", "") inf = inf.split(";") for i in inf: if "BioSample" in i: outd["biosample"] = i.strip(" ").replace("BioSample: ", "") # print(outd) return outd
def continentName(Weather): countryalpha = pc.country_name_to_country_alpha2(Weather.country, cn_name_format="default") countrycode = pc.country_alpha2_to_continent_code(countryalpha) continent = pc.convert_continent_code_to_continent_name(countrycode) return str(continent)
def get_continent(self): if self.country is not None: continent_code = country_alpha2_to_continent_code( self.country_code.upper()) return convert_continent_code_to_continent_name(continent_code)
df['urban_population'] = urban_population.urban_population df = pd.merge(corres_country, df, right_on='country', left_on='Country Code') df.drop(columns='country', inplace=True) df.rename(columns={ 'Country Name': 'country_name', 'Country Code': 'country_code' }, inplace=True) res = [] for row in range(df.shape[0]): try: res.append( pc.convert_continent_code_to_continent_name( pc.country_alpha2_to_continent_code( pc.country_name_to_country_alpha2( df["country_name"][row])))) except: res.append(df["country_name"][row]) df["continent"] = res # Dash app app = dash.Dash(__name__, suppress_callback_exceptions=True) server = app.server country_options = [{ "label": country_name, "value": country_name } for country_name in df.country_name.unique()]
data = { 'user_id': str(user_id), 'created': str(timestamp), 'country_id': str(country_id), 'answer_country_id': str(answer_country_id) } stats.insert(data) return data if __name__ == "__main__": from pycountry import countries import pycountry_convert as pc def country_alpha2_to_continent_code(a2): if a2 == 'AQ': return 'AN' elif a2 == 'TF': return 'AN' elif a2 == 'EH': return 'AF' elif a2 == 'PN': return 'OC' elif a2 == 'SX': return 'NA' elif a2 == 'TL': return 'AS' elif a2 == 'UM': return 'NA' elif a2 == 'VA': return 'EU' else: return pc.country_alpha2_to_continent_code(a2) cc = pc.country_alpha2_to_continent_code('XK') c = pc.convert_continent_code_to_continent_name(cc) countries_pc = pc.convert_countries.list_country_alpha2() countries_p = [c.alpha_2 for c in countries] for a2 in countries_pc: country_alpha2_to_continent_code(a2) print(list(set(pc.convert_country_alpha2_to_continent_code.COUNTRY_ALPHA2_TO_CONTINENT_CODE.values()))) #database = Database() #database.get_statistics('26442581')