Creating a table using a list of strings - python-3.x

I am needing to convert a list of lists of strings into a three column table where the first column is 1 space longer than the longest string. I have figured out how to identify the longest string and how long it is, but getting the table to form has been quite tricky. Here is the program with the lists in it and it shows you that the longest one is 26 characters long.
def main():
mycities = [['Cape Girardeau', 'MO', '63780'], ['Columbia', 'MO', '65201'],
['Kansas City', 'MO', '64108'], ['Rolla', 'MO', '65402'],
['Springfield', 'MO', '65897'], ['St Joseph', 'MO', '64504'],
['St Louis', 'MO', '63111'], ['Ames', 'IA', '50010'], ['Enid',
'OK', '73773'], ['West Palm Beach', 'FL', '33412'],
['International Falls', 'MN', '56649'], ['Frostbite Falls',
'MN', '56650']]
col_width = max(len(item) for sub in mycities for item in sub)
print(col_width)
main()
Now I am just needing to get it to print off like this:
Cape Girardeau MO 63780
Columbia MO 65201
Kansas City MO 64108
Springfield MO 65897
St Joseph MO 64504
St Louis MO 63111
Ames IA 50010
Enid OK 73773
West Palm Beach FL 33412
International Falls MN 56649
Frostbite Falls MN 56650

You're off to the right start -- as an example given the specific structure to the lists you have, you can use the col_width you calculated to determine the number of spaces you'd need after the name of each city to append to the end of each city name:
for city in mycities:
# append the string with the number of spaces required
city_padded = city[0] + " " + " "*(col_width-len(city[0]))
print(city_padded + city[1] + " " + city[2])
Given your example, this will produce:
Cape Girardeau MO 63780
Columbia MO 65201
Kansas City MO 64108
Rolla MO 65402
Springfield MO 65897
St Joseph MO 64504
St Louis MO 63111
Ames IA 50010
Enid OK 73773
West Palm Beach FL 33412
International Falls MN 56649
Frostbite Falls MN 56650
Note in the original version of your question, you are missing commas in your sublists in your mycities variable, for which I've added in an edit.
As a side note, it is convention in Python that words be separated by underscores in variable names for readability, so you might rename mycities to my_cities.
pep8 ref: (https://www.python.org/dev/peps/pep-0008/#function-and-variable-names)

"String name".ljust(26) will add spaces to the end of your string. For example,
Ames.ljust(26) will result in 'Ames (22 spaces here)', and then the next column will print after. If you are not sure what the longest city will be, you could replace the 26 with len(cities[-1]) after ordering the cities in a list by length. To do this, you can do sortedCities = sorted(cityListVariable, key=len)

def main():
cities = ['Cape Girardeau, MO 63780', 'Columbia, MO 65201', 'Kansas City, MO 64108', 'Rolla, MO 65402',
'Springfield, MO 65897', 'St Joseph, MO 64504', 'St Louis, MO 63111', 'Ames, IA 50010',
'Enid, OK 73773', 'West Palm Beach, FL 33412', 'International Falls, MN 56649', 'Frostbite Falls, MN 56650',
'Charlotte, NC 28241', 'Upper Marlboro, MD 20774', 'Camdenton, MO 65020', 'San Fransisco, CA 94016'] #create list of information
for x in cities:
col = x.split(",")
if(len(col) == 2):
city = col[0].strip()
temp = col[1].strip()
else:
city = x[:15].strip()
temp = c[15:].strip()
state = temp[:2]
zipCode = int(temp[-5::])
print("%-20s\t%s\t%d"%(city, state, zipCode))
main()

Related

Printing different image for different list data

so i made a list and i used tkinter for choosing a random data in list and showing that in a showinfo box. now i was just wondering if its possible to make a random image for random data.
for eg i am making a app that generates a random anime name from the list but i want to add the anime picture also is there any way i can do that ?
i haven't tried building it but here is what i have made so far.
i have no error i just want to have different picture for different names from the list chose randomly
import random
from tkinter import*
from tkinter import messagebox
anime = [
"1 Ore ga Ojousama Gakkou ni ' Shomin Sample' Toshite Gets♥Sareta Ken",
"2 Ookami to Koushinryou II",
"3 Ookami to Koushinryou",
"4 Grisaia no Kajitsu",
"5 Nyanko Days",
"6 Suzumiya Haruhi no Shoushitsu",
"7 Ookami Kodomo no Ame to Yuki",
"8 Sankarea",
"9 Boku no Hero Academia the Movie 2: Heroes Rising",
"10 Tensei shitara Slime Datta Ken OVA",
"11 Nakitai Watashi wa Neko wo Kaburu ",
"12 Tensei shitara Slime Datta Ken",
"13 Nande Koko ni Sensei ga!?",
"14 Kotonoha no Niwa",
"15 Chuunibyou demo Koi ga Shitai! Movie: Take On Me",
"16 Byousoku 5 Centimeter",
"17 Summer Wars",
"18 Tenki no Ko ",
"19 Kimi no Na wa.",
"20 Sword Art Online: Alicization – War of Underworld",
"21 Hinamatsuri",
"22 Gakuen Babysitters ",
"23 Yahari Ore no Seishun Love Comedy wa Machigatteiru. Zoku",
"24 Yahari Ore no Seishun Love Comedy wa Machigatteiru.",
"25 Hataraku Maou-sama!",
"26 Shokugeki no Souma: Shin no Sara",
"27 Shokugeki no Souma: San no Sara – Toutsuki Ressha-hen",
"28 Sewayaki Kitsune no Senko-san",
"29 Shokugeki no Souma: San no Sara",
"30 Shokugeki no Souma: Ni no Sara",
"31 Shokugeki no Soma ",
"32 Ao no Exorcist ",
"33 Ao no Exorcist: Kyoto Fujouou-hen",
"34 Boku dake ga Inai Machi",
"35 Kono Subarashii Sekai ni Shukufuku wo!: Kurenai Densetsu",
"36 Hyouka",
"37 Kami no Tou",
"38 Youkoso Jitsuryoku Shijou Shugi no Kyoushitsu e",
"39 Shingeki no Kyojin Season 3",
"40 Kaguya-sama wa Kokurasetai?: Tensai-tachi no Renai Zunousen 2nd Season",
"41 Shingeki no Kyojin Season 3 Part 2",
"42 Shingeki no Kyojin Season 2",
"43 Shingeki no Kyojin ",
"44 Kono Subarashii Sekai ni Shukufuku wo! 2",
"45 Seishun Buta Yarou wa Yumemiru Shoujo no Yume wo Minai",
"46 Kono Subarashii Sekai ni Shukufuku wo!",
"47 Seishun Buta Yarou wa Bunny Girl Senpai no Yume wo Minai",
"48 Sakurasou no Pet na Kanojo",
"49 Tate no Yuusha no Nariagari",
"50 IS: Infinite Stratos",
"51 Kawaikereba Hentai demo Suki ni Natte Kuremasu ka?",
"52 Enen no Shouboutai",
"53 Kaguya-sama wa Kokurasetai: Tensai-tachi no Renai Zunousen",
"54 Chuunibyou demo Koi ga Shitai! Ren",
"55 Koe no Katachi ",
"56 Dr. Stone",
"57 One Punch Man",
"58 Naruto Shippuden",
"59 Sword Art Online II",
"60 Sword Art Online",
"61 Ansatsu Kyoushitsu 2nd season",
"62 Ansatsu Kyoushitsu",
"63 Chuunibyou demo Koi ga Shitai!",
"64 Kimetsu no Yaiba",
"65 Re:Zero kara Hajimeru Isekai Seikatsu",
"66 Nanatsu no Taizai",
"67 Steins;Gate 0",
"68 Steins;Gate",
"69 Nanatsu no Taizai: Imashime no Fukkatsu",
"70 Tokyo Ghoul √A",
"71 One Punch Man Season 2",
"72 Hunter x Hunter (2011)",
"73 Darling in the FranXX",
"74 Tokyo Ghoul",
"75 Boku no Hero Academia 3rd Season.",
"76 Boku no Hero Academia",
"77 Nanatsu no Taizai: Kamigami no Gekirin",
"78 Naruto",
"79 Boku no Hero Academia 4th Season",
"80 Arte",
"81 Yakusoku no Neverland",
"82 Aho Girl",
"83 Wotaku ni Koi wa Muzukashii",
"84 Kimi no Suizou wo Tabetai ",
"85 Sakasama no Patema",
"86 Grisaia no Rakuen",
"87 Kimi ni Todoke",
"88 Kimi ni Todoke 2nd Season",
"89 Sukitte Ii na yo.",
"90 Ore wo Suki nano wa Omae dake ka yo",
"91 Koi To Uso",
"92 Saijaku Muhai no Bahamut",
"93 7 seeds",
"94 7 Seeds 2nd Season",
"95 Kono Yo no Hate de Koi wo Utau Shoujo YU-NO",
"96 Gotoubun no Hanayome",
"97 Masamune-kun no Revenge",
"98 Tokyo Magnitude 8.0",
"99 Keppeki Danshi! Aoyama-kun Episode ",
"100 Ao Haru Ride",
"101 Kakegurui",
"102 Kakegurui××",
"103 Tokyo Ghoul:re",
"104 Tokyo Ghoul:re 2nd season",
"105 Toradora!",
"106 Sounan Desu ka?",
"107 Denpa Onna to Seishun Otoko",
"108 Zenonzard The Animation",
"109 Hanamaru Kindergarden",
"110 Tonari no Kaibutsu-kun",
"111 Domestic na Kanojo",
"112 Haikyuu!!",
"113 Haikyuu!! Second Season",
"114 Haikyuu!!: Karasuno Koukou vs. Shiratorizawa Gakuen Koukou",
"115 Haikyuu!!: To the Top",
"116 Sword Art Online: Alicization – War of Underworld 2nd Season",
"117 Haikyuu!!: To the Top",
"118 Yahari Ore no Seishun Love Comedy wa Machigatteiru. Kan",
"119 Kanojo, Okarishimasu",
"120 Shokugeki no Souma: Gou no Sara",
"121 Maou Gakuin no Futekigousha: Shijou Saikyou no Maou no Shiso, Tensei shite Shison-tachi no Gakkou e",
"122 UZAKI-CHAN WA ASOBITAI!",
"123 ReLIFE",
"124 ReLIFE: Kanketsu-hen",
"125 The God of High School",
"126 Inou-Battle wa Nichijou-kei no Naka de",
"127 Kyoukai no Kanata",
"128 Arifureta Shokugyou de Sekai Saikyou",
"129 ISEKAI MAOU TO SHOUKAN SHOUJO NO DOREI MAJUTSU",
"130 AKAME GA KILL!",
"131 Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season",
"132 Shinchou Yuusha: Kono Yuusha ga Ore Tueee Kuse ni Shinchou Sugiru",
"133 Noragami",
"134 Noragami OVA",
"135 Noragami Aragoto",
"136 Nisekoi",
"137 Nisekoi:",
"138 Black Bullet",
"139 Devils Line",
"140 TABOO TATTOO",
"141 Hajimete no Gal ",
"142 Kuzu no Honkai",
"143 Tsurezure Children",
"144 Himouto! Umaru-chan",
"145 Boku no Kanojo ga Majimesugiru Sho-bitch na Ken",
"146 Bungou Stray Dogs",
"147 Bungou Stray Dogs Season 2",
"148 Bungou Stray Dogs 3rd Season",
"149 Lovely★Complex",
"150 Plunderer",
"151 TONIKAKU KAWAII",
"152 Enen no Shouboutai: Ni no Shou",
"153 Haikyuu!!: To the Top 2nd Season",
"154 Shigatsu wa Kimi no Uso",
"155 Kaichou wa Maid-sama",
"156 Karakai Jouzu no Takagi-san",
"157 Karakai Jouzu no Takagi-san 2"]
top = Tk()
top.geometry("200x100")
def fun():
messagebox.showinfo("Anime", random.choice(anime))
can = Canvas(top, height = 100, width = 100)
can.place(relx=0.5, rely=0.5, anchor=CENTER)
b1 = Button(can,text = "Generate",command = fun,activeforeground = "black",activebackground = "yellow",pady=10)
b1.pack(side = TOP)
top.mainloop()
Since you want the image to be corresponding to the anime titles I suggest you use a dictionary instead of a list. Also, use Toplevel widget to display the output.
So here is an example code:
import random
from tkinter import*
from PIL import Image, ImageTk
absolute_path = r'C:\Users\ ' # your absolute path goes here(Note: Don't remove the extra space in the end)
anime = {
"1 Ore ga Ojousama Gakkou ni ' Shomin Sample' Toshite Gets♥Sareta Ken": 'Akira.png', # anime image name
"2 Ookami to Koushinryou II": 'Alex.jpg', # anime image name
}
root = Tk()
root.geometry("200x100")
def fun():
top = Toplevel(root)
top.title('Anime')
random_choice = random.choice(list(anime.keys())) #choosing random from dictionary keys
label = Label(top, text=random_choice)
label.pack()
top.img = ImageTk.PhotoImage(Image.open(absolute_path.strip()+anime[random_choice]))
image_label = Label(top, image=top.img)
image_label.pack()
can = Canvas(root, height = 100, width = 100)
can.place(relx=0.5, rely=0.5, anchor=CENTER)
b1 = Button(can,text = "Generate",command = fun,activeforeground = "black",activebackground = "yellow",pady=10)
b1.pack(side = TOP)
root.mainloop()

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.

In a comma delimited String, keep all but second part

I have a bunch of addresses:
123 Main Street, PO Box 345, Chicago, IL 92921
1992 Super Way, Bakersfield, CA
234 Wonderland Lane, Attn: Daffy Duck, Orlando, FL 09922
How could I cut out the second string in there, when I do myStr.split(',') on each?
The idea is that I want to return:
123 Main Street, Chicago, IL 92921
1992 Super Way, CA
234 Wonderland Lane, Orlando, FL 09922
I could loop through each part, and build yet another string, skipping the second index, but was wondering if there's a better way to do so.
What I have now:
def filter_address(address):
print("Filtering address on",address)
updated_addr = ""
indx = 0
for section in address.split(","):
if indx != 1:
updated_addr = updated_addr + "," + section
indx += 1
updated_addr = updated_addr[1:] # This is to remove the leading `,`
new_address = filter_address("123 Main Street, Chicago, IL 92921")
You could use del in python and glue back the components of the string with ", " after splitting them.
For example:
address = "123 Main Street, PO Box 345, Chicago, IL 92921".split(",")
del address[1]
pretty_address = ", ".join(address)
print(pretty_address) # Gives 123 Main Street, Chicago, IL 92921

Reading a specific txt file and re-arrange it to a given format

Below is an output of Chemichal analysis instrument. I need to rearrange the format and sort it in a way that percentage figure for each element goes below its name. My question is how to read this file word by word? how can I choose, for instance word number 12?
txt file format:
Header_1 Date Time Method_Name (Filter_Name) Calc_Mode Heat No. Quality Anal. Code Sample ID C Si Mn P S Cr Mo Ni Al Co Cu Nb Ti V W Pb Sn As Bi Ca Sb Se B Zn N Fe Place Code Work Phase
Single 13.01.13 09:51:10 Fe-10 Test AutoResult 12A 00001.040 00000.437 00000.292 00000.023 00000.007 00001.505 00000.263 00000.081 00000.012 00000.014 00000.110 00000.155 00000.040 00000.098 00000.015 00000.014 00000.013 00000.012 00000.002 00000.001 00000.016 00000.014 00000.005 00000.001 00000.016 00095.813
To find word 12, read the line character by character until you have seen 11 instances of whatever is being used to separate words (which you have not specified); what follows, until the next such separator, will be the 12th word.

Resources