def getPopulation(country):
    try:
        country = CountryInfo(country)
        popoulation = country.population()
    except:
        popoulation = 10000000
    return popoulation
示例#2
0
    async def states(self, ctx, *, country):
        data = await country_filter(country, ctx)
        if data is None:
            return

        country = data["name"]
        country1 = CountryInfo(country)

        result = country1.provinces()

        for i, x in enumerate(result):
            result[i] = "`" + x + "`"

        result1 = " |".join(result)

        result2 = re.sub(r"(?<=[|])(?=[^\s])", r" ", result1)

        embed = discord.Embed(
            title="States of " + country,
            description="**{result2}**".format(result2=result2),
            color=0xFF5733,
        )

        result4 = coco.convert(names=country, to="ISO2")
        embed.set_thumbnail(
            url=f"https://flagcdn.com/w80/{result4.lower()}.jpg")

        embed.set_footer(
            text="Requested by: {name}".format(name=ctx.author),
            icon_url=ctx.author.avatar_url,
        )

        await ctx.send(embed=embed)
示例#3
0
async def country_info(update: Message):
    country = update.text.split(" ", 1)[1]
    country = CountryInfo(country)
    info = f"""--**Country Information**--

Name : `{country.name()}`
Native Name : `{country.native_name()}`
Capital : `{country.capital()}`
Population : `{country.population()}`
Region : `{country.region()}`
Sub Region : `{country.subregion()}`
Top Level Domains : `{country.tld()}`
Calling Codes : `{country.calling_codes()}`
Currencies : `{country.currencies()}`
Residence : `{country.demonym()}`
Timezone : `{country.timezones()}`

Made by **@XD_Botz ❤️**"""
    country_name = country.name()
    country_name = country_name.replace(" ", "+")
    reply_markup = InlineKeyboardMarkup([[
        InlineKeyboardButton('Wikipedia', url=f'{country.wiki()}'),
        InlineKeyboardButton(
            'Google', url=f'https://www.google.com/search?q={country_name}')
    ]])
    try:
        await update.reply_text(text=info,
                                reply_markup=reply_markup,
                                disable_web_page_preview=True,
                                quote=True)
    except Exception as error:
        await update.reply_text(text=error,
                                disable_web_page_preview=True,
                                quote=True)
示例#4
0
def plotdata():
    try:
        country = data.get()
        country = country.strip()
        country = country.replace(" ", ",").split(",")
        countries = []
        for x in country:
            countries.append(x)
        df = pd.read_csv(
            'https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv',
            parse_dates=['Date'])
        df = df[df['Country'].isin(countries)]
        #Creating a Summary Column
        df['Cases'] = df[['Confirmed', 'Recovered', 'Deaths']].sum(axis=1)
        #Restructuring our Data
        df = df.pivot(index='Date', columns='Country', values='Cases')
        countries = list(df.columns)
        covid = df.reset_index('Date')
        covid.set_index(['Date'], inplace=True)
        covid.columns = countries
        #Calculating Rates per 100,000
        populations = {}
        for i in countries:
            c = CountryInfo(i)
            populations[i] = c.population()
        percap = covid.copy()
        for country in list(percap.columns):
            percap[country] = percap[country] / populations[country] * 100000
        #Generating Colours
        colors = {}
        k = 0
        col = ['#045275', '#089099', '#DC3977', '#7C1D6F', '#7CCBA2']
        for i in countries:
            colors[i] = col[k]
            k += 1
        plt.style.use('fivethirtyeight')
        percapplot = percap.plot(figsize=(12, 8),
                                 color=list(colors.values()),
                                 linewidth=5,
                                 legend=False)
        percapplot.grid(color='#d4d4d4')
        percapplot.set_xlabel('Month', color='brown')
        percapplot.set_ylabel('# of Cases per 100,000 People', color='brown')
        for country in list(colors.keys()):
            percapplot.text(x=percap.index[-1],
                            y=percap[country].max(),
                            color=colors[country],
                            s=country,
                            weight='bold')
        percapplot.text(
            x=percap.index[2],
            y=percap.max().max() + 45,
            s=
            "Covid-19 Comparison Graph Between Countries \nIncludes Current Cases, Recoveries, and Deaths",
            fontsize=18,
            color='brown',
            alpha=.75)
        plt.show()
    except Exception as e:
        print("Country data not present ")
def get_country_coord(country):
    country_off = pycountry.countries.search_fuzzy(country)[0].official_name
    c = CountryInfo(country_off)
    try:
        capital = c.capital()
    except KeyError:
        capital = CountryInfo(country).capital()
    return (get_country_city_coord(country, capital))
示例#6
0
def is_country_name_valid(name: str) -> bool:
    rv = True
    try:
        c = CountryInfo(name)
        data = c.native_name()
    except KeyError:
        rv = False
    return rv
示例#7
0
 def setUp(self):
     """Loads all the countries just once for all the tests
     """
     if not self.all_countries:
         print("Loading all countries...")
         country_names = CountryInfo().all()
         for name in country_names:
             country = CountryInfo(name)
             self.all_countries[name] = country
示例#8
0
 def languages(self, request, alpha_2):
     """
     Send languages for a specific country
     """
     try:
         c = CountryInfo(alpha_2)
         return Response(c.languages(), content_type="application/json")
     except KeyError:
         return Response("Unknown country or no info for this country",
                         status=HTTP_404_NOT_FOUND)
示例#9
0
    def __init__(self, city, country):
        self.forecastTempMax = []
        self.forecastTempMin = []
        self.forecastDates = []
        self.city = city
        self.country = country

        self.place = wthmgr.weather_at_place(self.city + ', ' + self.country)

        self.status = self.place.weather.detailed_status
        self.temp = int(
            round(self.place.weather.temperature('celsius')['temp'], 1))
        self.wind = round(self.place.weather.wind('km_hour')['speed'], 2)
        self.pressure = self.place.weather.pressure['press']
        self.sunrise = self.place.weather.sunrise_time(timeformat="date")
        self.sunset = self.place.weather.sunset_time(timeformat="date")
        self.tempDif = self.place.weather.temperature('celsius')
        self.tempMax = round(self.tempDif['temp_max'], 1)
        self.tempMin = round(self.tempDif['temp_min'], 1)

        self.lat = geolocator.geocode(self.city + ',' + self.country).latitude
        self.long = geolocator.geocode(self.city + ',' +
                                       self.country).longitude

        self.capitol = CountryInfo(self.country).capital()
        self.dailyForecaster = wthmgr.forecast_at_place(
            self.city + ', ' + self.country, '3h')
        self.oneCallForecast = wthmgr.one_call(self.lat,
                                               self.long).forecast_daily
        self.continent = continentName(self)
        self.continent = checkUS(self.continent)
        self.citySpace = self.city.replace(' ', '_')

        try:
            self.timezone = self.continent + '/' + self.citySpace

        except:
            self.timezone = CountryInfo(str(
                self.country)).timezones()[0] + '/' + self.citySpace

        self.zone = pytz.timezone(self.timezone)
        self.time = int(datetime.now(self.zone).hour)
        self.image = setImage(self)
        self.sunrise = self.sunrise.replace(tzinfo=pytz.utc).astimezone(
            self.zone)
        self.sunset = self.sunset.replace(tzinfo=pytz.utc).astimezone(
            self.zone)

        self.coldest = self.dailyForecaster.most_cold()
        self.hottest = self.dailyForecaster.most_hot()
        self.rainest = self.dailyForecaster.most_rainy()
        self.snowy = self.dailyForecaster.most_snowy()

        self.longTermForecast()
示例#10
0
def get_capital():
    with sr.Microphone() as source:
        print("What country would you like to know the capital of: ")
        audio = r.listen(source)
    try:
        country_said = r.recognize_google(audio)
    except:
        print("Could not recognize your voice")
    try:
        country = CountryInfo(country_said)
        print("The capital of " + country_said + " is " + country.capital() + ".")
示例#11
0
def population(message):
    message = message.replace('!population ', '')
    message = message.replace('!population', '')
    if message == '':
        return 'Please specify country.'
    else:
        countryinfo = CountryInfo(message)
        message = message.replace(message[0], message[0].upper())
        message = message.replace(message[1:], message[1:].lower())
        return "The population of " + message + " is " + str(
            countryinfo.population() + ".")
示例#12
0
def capital(message):
    message = message.replace('!capital ', '')
    message = message.replace('!capital', '')
    if message == '':
        return 'Please specify country.'
    else:
        countryinfo = CountryInfo(message)
        message = message.replace(message[0], message[0].upper())
        message = message.replace(message[1:], message[1:].lower())
        return "The capital of " + message + " is " + str(
            countryinfo.capital() + ".")
示例#13
0
def pizda(message):
    # country = next((x for x in data if x['country'] == message.text))
    country = None
    for x in data:
        if x['country'] == message.text:
            country = x

    if message.text == "World":
        bot.send_message(
            message.chat.id, f"По миру:\n"
            f" Подтверждено - {country['confirmed']},\n"
            f" Cмертей  - {country['deaths']},\n"
            f" Выздоровело - {country['recovered']}\n")
    elif message.text == 'Back':
        # keyboard
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        item1 = types.KeyboardButton('Belgium')
        item2 = types.KeyboardButton('World')
        item3 = types.KeyboardButton('Netherlands')
        item4 = types.KeyboardButton('Italy')
        item5 = types.KeyboardButton('Russia')
        item6 = types.KeyboardButton("Other")
        markup.row(item2)
        markup.row(item1, item5, item3)
        markup.row(item4, item6)
        bot.send_message(
            message.chat.id,
            'Посмотри на клавиатуру и выбери свою страну или напиши в сообщении. Например "Russia"',
            reply_markup=markup)
    elif isinstance(country, dict):
        if message.text == "USA":
            population = CountryInfo("United States").population()
        else:
            population = CountryInfo(message.text).population()
        bot.send_message(
            message.chat.id, f"В стране:\n"
            f"Численность населения - {population}\n"
            f" Подтверждено - {country['confirmed']},\n"
            f" Cмертей  - {country['deaths']},\n"
            f" Выздоровело - {country['recovered']}\n")
    elif message.text == "Other":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        items = [types.KeyboardButton(x['country']) for x in data]
        items.insert(0, types.KeyboardButton('Back'))
        markup.add(*items)
        bot.send_message(
            message.chat.id,
            'Посмотри на клавиатуру и выбери свою страну или напиши в сообщении. Например "Russia"',
            reply_markup=markup)

    else:
        bot.send_message(message.chat.id, "No such country")
示例#14
0
def get_country_population_and_continent(country: str, ) -> Tuple[int, str]:
    try:
        country_translated = (country if country
                              not in COUNTRIES_TRANSLATE_TO_COUNTRYINFO.keys()
                              else COUNTRIES_TRANSLATE_TO_COUNTRYINFO[country])

        country_translated_info = CountryInfo(country_translated)
        population = country_translated_info.population()
        continent = country_translated_info.region()
    except KeyError:
        population, continent = -1, FILLNA

    return population, continent
 def set_info(country, info):
     try:
         new_country = str(country).strip().split(",")[0]
         return (country, CountryInfo(new_country).info()[info])
     except:
         try:
             new_country = pycountry.countries.search_fuzzy(
                 new_country)[0].official_name
             return (country, CountryInfo(new_country).info()[info])
         except:
             if if_print:
                 print(f"not found {info} for {country}")
             unknown.append(country)
             return (country, "")
示例#16
0
 def currencies(self, *args, **kwargs) -> []:
     """
     Return a list of currencies used in this country
     """
     from djangophysics.currencies.models import Currency
     from djangophysics.currencies.models import CurrencyNotFoundError
     ci = CountryInfo(self.alpha_2)
     currencies = []
     for currency in ci.currencies():
         try:
             currencies.append(Currency(code=currency))
         except CurrencyNotFoundError:
             pass
     return currencies
示例#17
0
文件: bot2.py 项目: Lalitha-12/Ml2021
def capital():
    i = 1
    while i > 0:
        a = input("Enter country name: ")
        if (a == "bye"):
            break
        else:
            s = a
            country = CountryInfo(s)
            print(country.capital())
            #it prints the capital of country
            print(country.currencies())
            #it prints currency of country
        i = i + 1
示例#18
0
def doCountry2Continent(args, df0):

    args.d_country2continent = {}
    args.d_country2continent['United States of America'] = 'North America'
    args.d_country2continent['EU'] = 'Europe'
    for country, d in CountryInfo().all().items():
        # print(country, d)
        try:
            args.d_country2pop[d['name']] = d['population'] / 10**6
            # args.d_country2continent[d['name']] = d['subregion']
            args.d_country2continent[d['name']] = d['region']
        except KeyError:
            pass
        if not d['ISO']['alpha3'] in df0['countryterritoryCode'].unique():
            continue
        country = df0[df0['countryterritoryCode'] == d['ISO']
                      ['alpha3']]['countriesAndTerritories'].unique()[0]
        try:
            args.d_country2pop[country] = d['population'] / 10**6
            # args.d_country2continent[d['name']] = d['subregion']
            args.d_country2continent[d['name']] = d['region']
        except KeyError:
            continue

    args.d_country2continent['Bahamas'] = 'Americas'

    return
示例#19
0
def createBorderDict(countrySet):
    borderDict = {}
    borderSet = set()
    for c in countrySet:
        try:
            borders = []
            country = CountryInfo(c)
            borders_codes = country.borders()
            for b in borders_codes:
                border = pycountry.countries.get(alpha_3=b).name
                borders.append(border)
                borderSet.add(border)
            borderDict[c] = borders
        except:
            borderDict[c] = borders

    return borderDict, borderSet
示例#20
0
def main():
    try:
        start_date = date(2020, 3, 1)
        end_date = date(2020, 10, 2)
        delta = timedelta(days=1)
        while start_date <= end_date:  
            day = start_date.strftime("%Y-%m-%d")  
            print ("Downloading " + day)    
            url = "https://api.covid19tracking.narrativa.com/api/" + day
            r = requests.get(url)
            data = r.json()    
            start_date += delta

            for day in data['dates']:
                for country in data['dates'][day]['countries']:
                    try:
                        country_info = CountryInfo(country)
                        country_iso_3 = country_info.iso(3)
                        population = country_info.population()
                    except Exception as e:
                        print("Error with " + country)
                        country_iso_3 = country
                        population = None
                        infection_rate=0
                        print(e)

                    if population != None:
                        try:
                            infection_rate=getInfectionRate(data['dates'][day]['countries'][country]['today_confirmed'], population)
                        except:
                            infection_rate=0

                    result_data = data['dates'][day]['countries'][country]
                    del result_data['regions']
                    result_data['timestamp'] = result_data.pop('date')
                    result_data.update(
                                timestamp=datetime.strptime(day, "%Y-%m-%d"),
                                country_iso_3=country_iso_3,
                                population=population,
                                infection_rate=infection_rate,
                                )

                    save_elasticsearch_es('covid-19-live-global',result_data)
    except Exception as e:
        print(e)
def get_latitute_and_longitude():
    """
    Imports capitals and shows their latitute and longitude
    
    ---format----
    { COUNTRY : ["Capital", [latitude, longitude]] }
    
    """
    lat_long_capitales = {}
    for pays, capitale in capitals.items():
        lat_long = CountryInfo(pays)
        try:
            lat_long = lat_long.capital_latlng()
        except:
            lat_long = "erreur"
        lat_long_capitales[pays] = [capitale, lat_long]

    return lat_long_capitales
示例#22
0
def generar_casos_porcentaje(df_data):
    df_prin = generar_casos("Deaths", df_data)
    unicos = df_prin["Country"].unique()
    pops = [CountryInfo(p).info()["population"] for p in unicos]
    df_pops = pd.DataFrame({"Country": unicos, "population": pops})

    df_prin = df_prin.merge(df_pops, on="Country", how="left")
    df_prin["percentage"] = df_prin["Deaths"] / df_prin["population"]
    return df_prin
示例#23
0
def user_geo(country_name="me"):
    if country_name == "me":
        code = geocoder.ip(country_name).country
        country = CountryInfo(code)
    else:
        country = CountryInfo(country_name)
        code = country.iso(2)
    capital = country.capital()
    name = country.name().capitalize()
    currency = country.currencies()
    return [code, name, capital, currency]
def readData(
    file
):  # file is the testing file, while Country_Name is a dictionary to hold the data
    f = open(file, "r")

    Country_Name = {}

    size = [0, 0, 0, 0, 0, 0]

    for line in f:
        meas = line.split(',')

        for i in range(1, 6):
            meas[i] = meas[i].strip()
            if meas[i] == "[]\n":
                meas[i] = "[0]\n"
            elif meas[i] == "[]":
                meas[i] = "[0]"
        #the sizes of each data value
        size[0] = len(meas[0])
        size[1] = len(meas[1])
        size[2] = len(meas[2])
        size[3] = len(meas[3])
        size[4] = len(meas[4])
        size[5] = len(meas[5])

        #using the countryingo library
        country = CountryInfo(meas[0][2:(size[0] - 2)])
        lat_lng = country.latlng()

        Country_Name[meas[0][2:(size[0] - 2)]] = {
            "Total_Cases": int(meas[1][1:(size[1] - 1)]),
            "New_Cases": int(meas[2][1:(size[2] - 1)]),
            "Total_Deaths": int(meas[3][1:(size[3] - 1)]),
            "Total_Recovered": int(meas[4][1:(size[4] - 1)]),
            "Active_Cases": int(meas[5][1:(size[5] - 1)]),
            "Latitude": lat_lng[0],
            "Longitude": lat_lng[1]
        }

    f.close()

    return Country_Name
示例#25
0
 def handle(self, *args, **options):
     """
     Handle call
     """
     datafile = os.path.join(os.path.dirname(__file__), '..', '..',
                             'data.py')
     currency_countries = {}
     from countryinfo import CountryInfo
     ci = CountryInfo()
     for value in ci.all().values():
         for currency in value.get('currencies', []):
             if currency in currency_countries:
                 currency_countries[currency].append(value['ISO']['alpha2'])
             else:
                 currency_countries[currency] = [
                     value['ISO']['alpha2'],
                 ]
     with open(datafile, "w") as fp:
         fp.write(f"CURRENCY_COUNTRIES = "
                  f"{json.dumps(currency_countries, indent=2)}\n")
    def random(cls):
        alpha_2 = None
        countries = list(pycountry.countries)
        while alpha_2 is None:
            alpha_2 = random.choice(countries).alpha_2
            try:
                CountryInfo(alpha_2).capital_latlng()
            except KeyError:
                alpha_2 = None

        return cls.from_alpha_2(alpha_2)
示例#27
0
def bordering_countries(country_name: str) -> set:
    """
    Finds bordering countries for the given country
    """
    rename_dct = {'United States': 'USA', 'United Kingdom': 'UK'}
    try:
        country = CountryInfo(country_name)
        converter = CountryConverter(include_obsolete=True)
        countries = converter.convert(country.borders(), to='name_short')
        if type(countries) == str:
            countries = {countries}
        else:
            countries = set(countries)
            countries.add(country_name)
        for name in rename_dct:
            if name in countries:
                countries.remove(name)
                countries.add(rename_dct[name])
        return countries
    except Exception:
        print('Invalid Country')
示例#28
0
def get_country_info(name_country, lang='en'):
    """
    Retorna pycountry

    Args:
        name_country:
        lang:

    Returns:
        country, nom_country_lang, limite_geojson, CountryInfo
    """
    r_country, r_country_name, r_limite_geojson, r_c_info = None, None, None, None

    trans = None
    if lang.lower() != 'en':
        trans = gettext.translation('iso3166',
                                    pycountry.LOCALES_DIR,
                                    languages=[lang])

    for country in pycountry.countries:
        if trans:
            trans_country_name = trans.gettext(country.name)
        else:
            trans_country_name = country.name

        c_info = CountryInfo(country.name)

        if name_country.strip().lower() == trans_country_name.lower():
            limite_geojson = None
            try:
                g_json = c_info.geo_json()
                if features := g_json.get('features'):
                    limite_geojson = str(features[0]['geometry'])
            except Exception:
                pass

            r_country, r_country_name, r_limite_geojson, r_c_info = country, trans_country_name, limite_geojson, c_info
            break

    return r_country, r_country_name, r_limite_geojson, r_c_info
示例#29
0
def on_handleLatLng(sid, data):
    coordinates = (data.get('lat'), data.get('lng')),
    location_info = reverse_geocode.search(coordinates)[0]
    country = location_info.get('country')
    try:
        country_info = CountryInfo(country).info()
    except:
        country_info = 'Unknow Country'
    SIO.emit('country_info', {
        'country_info': country_info,
        'location_info': location_info
    },
             room=sid)
示例#30
0
    def fill_index(self):
        str = "United States,Canada,Turkey,Sweden,Denmark,France,\
Germany,China,Singapore,Japan,Mexico,Australia,Norway,\
Brazil,South Korea,United Kingdom,Netherlands,Philippines,\
Guam,Israel,Peru,Spain,Switzerland,Costa Rica,\
Italy,Ireland,Iraq,New Zealand,Belgium,Croatia,\
United States Virgin Islands,Dominican Republic,\
Austria,Georgia,French Guiana,Christmas Island,El Salvador,\
Finland,Andorra,Gibraltar,\
Aruba,Chile,United Arab Emirates,Guyana,Thailand,Puerto Rico,\
Zimbabwe,Argentina,Venezuela,Ghana,Guatemala,Greece,\
Colombia,Hungary,Malta,Taiwan,Zambia,Portugal,Kuwait,\
Cape Verde,Honduras,Serbia,San Marino,Luxembourg,Bermuda,\
American Samoa,Comoros,Ukraine,Romania,\
French Southern and Antarctic Lands,Bangladesh,Saudi Arabia,Syria,\
Poland,Iceland,India,Armenia,British Virgin Islands,Panama,\
Hong Kong,Niger,Suriname,South Africa,\
Cayman Islands,Ecuador,Czech Republic,\
Heard Island and McDonald Islands,Uzbekistan,Vietnam,Russia,\
Afghanistan,Central African Republic,Paraguay,Nicaragua,Morocco,\
North Korea,British Indian Ocean Territory,Cuba,Uruguay,\
Belize,Jamaica,Bahamas,Senegal,Qatar,Jersey,\
Bolivia,Sudan,Belarus,Algeria,Trinidad and Tobago,Cyprus,\
Bosnia and Herzegovina,Western Sahara,Iran,Albania,Bahrain,\
Réunion,Burundi,Malaysia,Isle of Man,Cambodia,Barbados,\
Slovakia,Liechtenstein,South Georgia,\
Nigeria,Angola,Vatican City,Mongolia,South Sudan,\
Haiti,Indonesia,Oman,Lithuania,Mauritius,\
Guinea,Pakistan,Jordan,Libya,Palestine,Brunei,Grenada,\
Papua New Guinea,Lebanon,Azerbaijan,Cocos (Keeling) Islands,\
Anguilla,Sri Lanka,Somalia,Kenya,Latvia,Guadeloupe,\
Uganda,Pitcairn Islands,Bulgaria,Chad,Benin,Namibia,\
Northern Mariana Islands,Tunisia,New Caledonia,Egypt,Estonia,\
Madagascar,DR Congo,Slovenia,Montenegro,Guernsey,\
Faroe Islands,Botswana,Saint Lucia,Norfolk Island,Greenland,\
Kazakhstan,Djibouti,French Polynesia,Montserrat,\
Nepal,Myanmar,Ethiopia,Falkland Islands"                                          # Removed US, CA, blank and none, England, Wales, Scotland.
        # Need to deal with US and CA.
        # Territories with more significant overseas areas will be separate (contigious america, china france)

        region_list = list(str.split(","))

        iso_list = []
        for i in range(self.c_length):
            try:
                iso_list.append(CountryInfo(region_list[i]).iso(
                    alpha=2))  # for each country try to search for iso code
            except KeyError:
                iso_list.append(None)
        self.region_df.index = [region_list, iso_list]