I want to print the country capitals if the country is chosen - python-3.x

Here is the code:
import time
from colored import fg
import sys
clr1 = fg("red")
clr2 = fg("blue")
clr3 = fg("yellow")
clr4 = fg("green")
for x in (clr1 + "Hi,\nThis program is made to find out the capital city of countries. For now, there are only around 100 countries which you can find the capitals of.\nThe countries are:\n"):
sys.stdout.write(x)
sys.stdout.flush()
time.sleep(0.03)
time.sleep(1)
for x in (clr2 + "Afghanistan\nAlbania\nAlgeria\nArgentina\nArmenia\nAustralia\nAustria\nAzerbaijan\nBahrain\nBangladesh\nBelgium\nBenin\nBotswana\nBrazil\nBulgaria\nCanada\nChile\nColombia\nCostaRica\nCroatia\nCuba\nDenmark\nDjibouti\nDominica\nEgypt\nEritrea\nEstonia\nEthiopia\nFiji\nFinland\nFrance\nGabon\nGermnay\nGhana\nGreece\nGrenada\nGuinea\nHaiti\nHungary\nIceland\nIndia\nIndonesia\nIran\Ireland\nItaly\nJamaica\nJapan\nJordan\nKenya\nSouthKorea\nKosovo\nKuwait\nLaos\nLativa\nLebanon\nLiberia\nLibya\nLuxembourg\nMacedonia\nMadagascar\nMalawi\nMalaysia\nMaldives\nMali\nMexico\nMoldova\nMonaco\nMongolia\nMontenegro\nMorocco\nMozambique\nNamibia\nNepal\nNetherlands\nNewZealand\nNiger\nNigeria\nNorway\nOman\nPakistan\nPanama\nPhilippines\nPoland\nPortugal\nQatar\nRomania\nRussia\nSamoa\nSaudi Arabia\nSenegal\nSerbia\nSingapore\nSlovakia\nSomalia\nSouth Africa\nSpain\nSri Lanka\nSudan\nSwitzerland\nSyria\nTaiwan\nThailand\nUganda\nUnited Arab Emirates\nUnited Kingdom\nUnited States of America\nUruguay\nVatican City\nVietnam\nYemen\nZimbabwe\n\n\n"):
sys.stdout.write(x)
sys.stdout.flush()
time.sleep(0.003)
time.sleep(1)
countries = {
"Afghanistan": 'Kabul',
"Albania":'Tirana',
"Algeria":'Algeirs',
"Argentina":'Buenos Aires',
"Armenia":'Yerevan',
"Australia":'Cnaberra',
"Austria":'Vienna',
"Azerbaijan":'Baku',
"Bahrain":'Manama',
"Bangladesh":'Dhaka',
"Belgium":'Brussels',
"Benin":'Porto_Novo',
"Botswana":'Gaborone',
"Brazil":'Brasilia',
"Bulgaria":'Sofia',
"Canada":'Ottawa',
"Chile":'Santiago',
"Colombia":'Bogota',
"Costa Rica":'San Jose',
"Croatia":'Zagreb',
"Cuba":'Havana',
"Denmark":'Copenhagen',
"Djibouti":'Djibouti',
"Dominica":'Roseau',
"Egypt":'Cairo',
"Eritrea":'Asmara',
"Estonia":'Tallinn',
"Ethiopia":'Addis Ababa',
"Fiji":'Suva',
"Finland":'Helsinki',
"France":'Paris',
"Gabon":'Libreville',
"Germnay":'Berlin',
"Ghana":'Accra',
"Greece":'Athens',
"Grenada":'Saint Georges',
"Guinea":'Conakry',
"Haiti":'Port-au-Prince',
"Hungary":'Budapest',
"Iceland":'Reykjavik',
"India":'New Delhi',
"Indonesia":'Jakarta',
"Iran":'Tehran',
"Ireland":'Dublin',
"Italy":'Rome',
"Jamaica":'Kingston',
"Japan":'Tokyo',
"Jordan":'Amman',
"Kenya":'Nairobi',
"South Korea":'Seoul',
"Kosovo":'Pristina',
"Kuwait":'Kuwait City',
"Laos":'Vientiane',
"Lativa":'Riga',
"Lebanon":'Beirut',
"Liberia":'Monrovia',
"Libya":'Tripoli',
"Luxembourg":'Luxembourg',
"Macedonia":'Skopje',
"Madagascar":'Antananarivo',
"Malawi":'Lilongwe',
"Malaysia":'Kuala Lumpur',
"Maldives":'Male',
"Mali":'Bamako',
"Mexico":'Mexico City',
"Moldova":'Chisnau',
"Monaco":'Monaco',
"Mongolia":'Ulaanbaatar',
"Montenegro":'Podgorica',
"Morocco":'Rabat',
"Mozambique":'Maputo',
"Namibia":'Windhoek',
"Nepal":'Kathmandu',
"Netherlands":'Amsterdam',
"NewZealand":'Wellington',
"Niger":'Niamey',
"Nigeria":'Abuja',
"Norway":'Oslo',
"Oman":'Muscat',
"Pakistan":'Islamabad',
"Panama":'Panama City',
"Philippines":'Manila',
"Poland":'Warsaw',
"Portugal":'Lisbon',
"Qatar":'Doha',
"Romania":'Bucharest',
"Russia":'Moscow',
"Samoa":'Apia',
"Saudi Arabia":'Riyadh',
"Senegal":'Dakar',
"Serbia":'Belgrade',
"Singapore":'Singapore',
"Slovakia":'Bratislava',
"Somalia":'Mogadishu',
"South Africa":'Pretoria(administrative); Cape Town(legislative); Bloemfontein(judicary)',
"Spain":'Madrid',
"Sri Lanka":'Colombo; Sri Jayewardenepura Kotte(legislative)',
"Sudan":'Khartoum',
"Switzerland":'Bern',
"Syria":'Damascus',
"Taiwan":'Taipei',
"Thailand":'Bangkok or Krung Thep Maha Nakhon',
"Uganda":'Kampala',
"United Arab Emirates":'Abu Dhabi',
"United Kingdom":'London',
"United States of America":'Washington, D.C',
"Uruguay":'Montevideo',
"Vatican City":'Vatican City',
"Vietnam":'Hanoi',
"Yemen":'Sanaa',
"Zimbabwe":'Harare'
}
time.sleep(1)
user_input = input(clr3 + "What country's capital do you want to find out (That is in the list) ?\n>>> ")
So every time the user inputs a country, how do I make it so that it prints out the capital with the fewest possible lines of code. For example i enter France and it gives out Paris. I dont want to use if statements to go through every line and say if user_input == <> : print("Capital"). That way I will have to write the statements over a 100 times. Is there a way to solve this problem

try:
print(countries[user_input])
except KeyError: # If the user input wasn't found in the dictionary
print("Invalid Country!")

Related

Best way to handle element of dict that has multiple key/value pairs inside it

[{'id': 2, 'Registered Address': 'Line 1: 1 Any Street Line 2: Any locale City: Any City Region / State: Any Region Postcode / Zip code: BA2 2SA Country: GB Jurisdiction: Any Jurisdiction'}]
I have the above read into a dataframe and that is the output so far. The issue is I need to break out the individual elements - due to names of places etc the values may or may not have spaces in them - looking at the above my keys are Line 1, Line 2, City, Region / State, Postcode / Zip, Country, Jurisdiction.
Output required for the "Registered Address"-'key'is the keys and values
"Line 1": "1 Any Street"
"Line 2": "Any locale"
"City": "Any City"
"Region / State": "Any Region"
"Postcode / Zip code": "BA2 2SA"
"Country": "GB"
"Jurisdiction": "Any Jurisdiction"
Just struggling to find a way to get to the end result.I have tried to pop out and use urllib.prse but fell short - is anypone able to point me in the best direction please?
Tried to write a code that generalizes your question, but there were some limitations, regarding your data format. Anyway I would do this:
def address_spliter(my_data, my_keys):
address_data = my_data[0]['Registered Address']
key_address = {}
for i,k in enumerate(keys):
print(k)
if k == 'Jurisdiction:':
key_address[k] = address_data.split('Jurisdiction:')[1].removeprefix(' ').removesuffix(' ')
else:
key_address[k] = address_data.split(k)[1].split(keys[i+1])[0].removeprefix(' ').removesuffix(' ')
return key_address
were you can call this function like this:
my_data = [{'id': 2, 'Registered Address': 'Line 1: 1 Any Street Line 2: Any locale City: Any City Region / State: Any Region Postcode / Zip code: BA2 2SA Country: GB Jurisdiction: Any Jurisdiction'}]
and
my_keys = ['Line 1:','Line 2:','City:', 'Region / State:', 'Postcode / Zip code:', 'Country:', 'Jurisdiction']
As you can see It'll work if only the sequence of keys is not changed. But anyway, you can work around this idea and change it base on your problem accordingly if it doesn't go as expected.

Extracting countries from string

I am trying to go through a column of data frame in python 3. What I need to do is take from each row the country that it is mentioned and the number of times that country is mentioned.
i.e. if I have this row:
['[Aydemir, Deniz', ' Gunduz, Gokhan', ' Asik, Nejla] Bartin Univ, Fac Forestry, Dept Forest Ind Engn, TR-74100 Bartin, Turkey', ' [Wang, Alice] Lulea Univ Technol, Wood Technol, Skelleftea, Sweden']
it needs to output a list: ['Turkey', 'Sweden']
and if I have this row:
['[Fang, Qun', ' Cui, Hui-Wang] Zhejiang A&F Univ, Sch Engn, Linan 311300, Peoples R China', ' [Du, Guan-Ben] Southwest Forestry Univ, Kunming 650224, Yunnan, Peoples R China']
the output should be: ['China', 'China'].
I have written this code but it is not working as I want to:
from geotext import GeoText
sentence = df.iloc[0,0]
places = GeoText(sentence)
print(places.countries)
It prints only the country once and in some cases when it is USA it doesn't recognize the abbreviation. Can you help me figure out what to do?
l = [['[Aydemir, Deniz\', \' Gunduz, Gokhan\', \' Asik, Nejla] Bartin Univ, Fac Forestry, Dept Forest Ind Engn, TR-74100 Bartin, Turkey\', \' [Wang, Alice] Lulea Univ Technol, Wood Technol, Skelleftea, Sweden',1990],
['[Fang, Qun\', \' Cui, Hui-Wang] Zhejiang A&F Univ, Sch Engn, Linan 311300, Peoples R China\', \' [Du, Guan-Ben] Southwest Forestry Univ, Kunming 650224, Yunnan, Peoples R China',2005],
['[Blumentritt, Melanie\', \' Gardner, Douglas J.\', \' Shaler, Stephen M.] Univ Maine, Sch Resources, Orono, ME USA\', \' [Cole, Barbara J. W.] Univ Maine, Dept Chem, Orono, ME 04469 USA',2012]]
dataf = pd.DataFrame(l, columns = ['Authors', 'Year'])
I tried to do this code but I have the same problem, it doesn't give all the counties only one per row:
def find_country(n):
for c in pycountry.countries:
if str(c.name).lower() in n.lower():
return c.name
country1 = (dataf['Authors']
.replace(r"\bUSA\b", "United States", regex=True)
.apply(lambda x: find_country(x)))
USA does not seem to be detected correctly by geotext - it's worth trying to raise an issue with that package. As a workaround here, I replace USA with United States, which is correctly detected.
df = (dataf['Authors']
.replace(r"\bUSA\b", "United States", regex=True)
.apply(lambda x: geotext.GeoText(x).countries)
)
I'm not sure what you were doing before, but this will get the list of countries for each of the rows in Author, including duplicates.
0 [Turkey, Sweden]
1 [China, China]
2 [United States, United States]
Name: Authors, dtype: object
As mentioned in the comment, if you want to have an actual list of lists, just add tolist() to the end.
df.tolist()
[['Turkey', 'Sweden'], ['China', 'China'], ['United States', 'United States']]

Need to print 10 different question booklets(aka Forms) but not able to print 9 of them as only the last one gets created and printed

import random
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'NewMexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia'}
for quizNum in range(10):
quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w')
answerKeyFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w')
quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum + 1))
quizFile.write('\n\n')
states = list(capitals.keys())
random.shuffle(states)
for questionNum in range(40):
correctAnswer = capitals[states[questionNum]]
wrongAnswers = list(capitals.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions)
quizFile.write('%s. What is the capital of %s?\n' % (questionNum + 1,states[questionNum]))
for i in range(4):
quizFile.write(' %s. %s\n' % ('ABCD'[i], answerOptions[i]))
quizFile.write('\n')
answerKeyFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
quizFile.close()
answerKeyFile.close()
The remaining 9 booklets are created as .txt files but are blank. Where am I going wrong ?
Questions involve the capital cities of U.S.A
Expected file form is :
Name:
Date:
Period:
State Capitals Quiz (Form 1)
What is the capital of West Virginia?
A. Hartford
B. Santa Fe
C. Harrisburg
D. Charleston
What is the capital of Colorado?
A. Raleigh
B. Harrisburg
C. Denver
D. Lincoln
3......
and so on . Like that for all the other files(remaining 9 .txt files which get created) questions would have to be printed.But they just turn out to be blank.
Each question booklets has the same questions but are in different order(to prevent cheating)
You questions loop is outside of the file loop. This is causing all of the files to be opened before any questions are written, then the last opened file is what gets the questions 👍
I can post the fix later if needed, just on my phone right now.

Adding an integer after each printed line from dictonaries

I am learning how to program in Python 3 and I am working on a project that lets you buy a ticket to a movie. After that you can see your shopping cart with all the tickets that you have bought.
Now, I want after each printed line to add a integer.
For example: 1. Movie1 , 2. Movie2 , etc..
Here is my code that I use to print the films:
if choice == 3:
#try:
print("Daca doresti sa vezi ce filme sunt valabile, scrie exit.")
bilet = str(input("Ce film doresti sa vizionezi?: ").title())
pret = films[bilet]["price"]
cumperi = input("Doresti sa adaugi in cosul de cumparaturi {}$ (y/n)?".format(bilet)).strip().lower()
if cumperi == "y":
bani[0] -= pret
cos.append(bilet)
if choice == 4:
print (*cos, sep="\n")
You can use an integral variable and increase it's value whenever you perform a task.
example set count = 0 and when you does a task place this there count += 1.

Reformat csv file using python?

I have this csv file with only two entries. Here it is:
Meat One,['Abattoirs', 'Exporters', 'Food Delivery', 'Butchers Retail', 'Meat Dealers-Retail', 'Meat Freezer', 'Meat Packers']
First one is title and second is a business headings.
Problem lies with entry two.
Here is my code:
import csv
with open('phonebookCOMPK-Directory.csv', "rt") as textfile:
reader = csv.reader(textfile)
for row in reader:
row5 = row[5].replace("[", "").replace("]", "")
listt = [(''.join(row5))]
print (listt[0])
it prints:
'Abattoirs', 'Exporters', 'Food Delivery', 'Butchers Retail', 'Meat Dealers-Retail', 'Meat Freezer', 'Meat Packers'
What i need to do is that i want to create a list containing these words and then print them like this using for loop to print every item separately:
Abattoirs
Exporters
Food Delivery
Butchers Retail
Meat Dealers-Retail
Meat Freezer
Meat Packers
Actually I am trying to reformat my current csv file and clean it so it can be more precise and understandable.
Complete 1st line of csv is this:
Meat One,+92-21-111163281,Al Shaheer Corporation,Retailers,2008,"['Abattoirs', 'Exporters', 'Food Delivery', 'Butchers Retail', 'Meat Dealers-Retail', 'Meat Freezer', 'Meat Packers']","[[' Outlets Address : Shop No. Z-10, Station Shopping Complex, MES Market, Malir-Cantt, Karachi. Landmarks : MES Market, Station Shopping Complex City : Karachi UAN : +92-21-111163281 '], [' Outlets Address : Shop 13, Ground Floor, Plot 14-D, Sky Garden, Main Tipu Sultan Road, KDA Scheme No.1, Karachi. Landmarks : Nadra Chowrangi, Sky Garden, Tipu Sultan Road City : Karachi UAN : +92-21-111163281 '], ["" Outlets Address : Near Jan's Broast, Boat Basin, Khayaban-e-Roomi, Block 5, Clifton, Karachi. Landmarks : Boat Basin, Jans Broast, Khayaban-e-Roomi City : Karachi UAN : +92-21-111163281 View Map ""], [' Outlets Address : Gulistan-e-Johar, Karachi. Landmarks : Perfume Chowk City : Karachi UAN : +92-21-111163281 '], [' Outlets Address : Tee Emm Mart, Creek Vista Appartments, Khayaban-e-Shaheen, Phase VIII, DHA, Karachi. Landmarks : Creek Vista Appartments, Nueplex Cinema, Tee Emm Mart, The Place City : Karachi Mobile : 0302-8333666 '], [' Outlets Address : Y-Block, DHA, Lahore. Landmarks : Y-Block City : Lahore UAN : +92-42-111163281 '], [' Outlets Address : Adj. PSO, Main Bhittai Road, Jinnah Supermarket, F-7 Markaz, Islamabad. Landmarks : Bhittai Road, Jinnah Super Market, PSO Petrol Pump City : Islamabad UAN : +92-51-111163281 ']]","Agriculture, fishing & Forestry > Farming equipment & services > Abattoirs in Pakistan"
First column is Name
Second column is Number
Third column is Owner
Forth column is Business type
Fifth column is Y.O.E
Sixth column is Business Headings
Seventh column is Outlets (List of lists containing every branch address)
Eighth column is classification
There is no restriction of using csv.reader, I am open to any technique available to clean my file.
Think of it in terms of two separate tasks:
Collect some data items from a ‘dirty’ source (this CSV file)
Store that data somewhere so that it’s easy to access and manipulate programmatically (according to what you want to do with it)
Processing dirty CSV
One way to do this is to have a function deserialize_business() to distill structured business information from each incoming line in your CSV. This function can be complex because that’s the nature of the task, but still it’s advisable to split it into self-containing smaller functions (such as get_outlets(), get_headings(), and so on). This function can return a dictionary but depending on what you want it can be a [named] tuple, a custom object, etc.
This function would be an ‘adapter’ for this particular CSV data source.
Example of deserialization function:
def deserialize_business(csv_line):
"""
Distills structured business information from given raw CSV line.
Returns a dictionary like {name, phone, owner,
btype, yoe, headings[], outlets[], category}.
"""
pieces = [piece.strip("[[\"\']] ") for piece in line.strip().split(',')]
name = pieces[0]
phone = pieces[1]
owner = pieces[2]
btype = pieces[3]
yoe = pieces[4]
# after yoe headings begin, until substring Outlets Address
headings = pieces[4:pieces.index("Outlets Address")]
# outlets go from substring Outlets Address until category
outlet_pieces = pieces[pieces.index("Outlets Address"):-1]
# combine each individual outlet information into a string
# and let ``deserialize_outlet()`` deal with that
raw_outlets = ', '.join(outlet_pieces).split("Outlets Address")
outlets = [deserialize_outlet(outlet) for outlet in raw_outlets]
# category is the last piece
category = pieces[-1]
return {
'name': name,
'phone': phone,
'owner': owner,
'btype': btype,
'yoe': yoe,
'headings': headings,
'outlets': outlets,
'category': category,
}
Example of calling it:
with open("phonebookCOMPK-Directory.csv") as f:
lineno = 0
for line in f:
lineno += 1
try:
business = deserialize_business(line)
except:
# Bad line formatting?
log.exception(u"Failed to deserialize line #%s!", lineno)
else:
# All is well
store_business(business)
Storing the data
You’ll have the store_business() function take your data structure and write it somewhere. Maybe it’ll be another CSV that’s better structured, maybe multiple CSVs, a JSON file, or you can make use of SQLite relational database facilities since Python has it built-in.
It all depends on what you want to do later.
Relational example
In this case your data would be split across multiple tables. (I’m using the word “table” but it can be a CSV file, although you can as well make use of an SQLite DB since Python has that built-in.)
Table identifying all possible business headings:
business heading ID, name
1, Abattoirs
2, Exporters
3, Food Delivery
4, Butchers Retail
5, Meat Dealers-Retail
6, Meat Freezer
7, Meat Packers
Table identifying all possible categories:
category ID, parent category, name
1, NULL, "Agriculture, fishing & Forestry"
2, 1, "Farming equipment & services"
3, 2, "Abattoirs in Pakistan"
Table identifying businesses:
business ID, name, phone, owner, type, yoe, category
1, Meat One, +92-21-111163281, Al Shaheer Corporation, Retailers, 2008, 3
Table describing their outlets:
business ID, city, address, landmarks, phone
1, Karachi UAN, "Shop 13, Ground Floor, Plot 14-D, Sky Garden, Main Tipu Sultan Road, KDA Scheme No.1, Karachi", "Nadra Chowrangi, Sky Garden, Tipu Sultan Road", +92-21-111163281
1, Karachi UAN, "Near Jan's Broast, Boat Basin, Khayaban-e-Roomi, Block 5, Clifton, Karachi", "Boat Basin, Jans Broast, Khayaban-e-Roomi", +92-21-111163281
Table describing their headings:
business ID, business heading ID
1, 1
1, 2
1, 3
…
Handling all this would require a complex store_business() function. It may be worth looking into SQLite and some ORM framework, if going with relational way of keeping the data.
You can just replace the line :
print(listt[0])
with :
print(*listt[0], sep='\n')

Resources