I have a list formatted like the following:
list_of_DVDsuppliers=[["a","m",15],["w","p",34]]
I'd like to print out the contents of this list as a table with some headers. Here's what I've tried so far:
def dvdprintsoftlist():
print(list_of_DVDsoftwears)
''' printing the available DVDstocks,supplier's details '''
print("This is your current list of stock")
print("Supplier Name Softwear Name Amount")
print("----------------------------------------------------------------")
for (index,[name,softname,amount]) in enumerate (list_of_DVDsuppliers):
print(name + " " +softname + " " +str(amount) + " ")
print("----------------------------------------------------------------")
print("")
The problem is that this code doesn't align the table columns properly. How can I make sure all the entries are aligned with each other?
I'd also like to export my data in CSV format so that other programs can read it, but that's a separate question.
You could use format(), the {i:length} in string, will be replaced by the parameters, where i is an order identifier, and length is the "length" of the field.
def dvdprintsoftlist():
list_of_DVDsuppliers=[["a","m",15],["w","p",34]]
print(list_of_DVDsuppliers)
print
''' printing the available DVDstocks,supplier's details '''
print("This is your current list of stock")
print("Supplier Name\t\tSoftwear Name\t\tAmount")
print("----------------------------------------------------------------")
for [name, softname, amount] in list_of_DVDsuppliers:
print("{0:23} {1:23} {2:5}".format(name, softname, amount))
print("----------------------------------------------------------------")
print("")
dvdprintsoftlist()
Try using the padding bits between the % and s while printing
you can use them like...
print('%-20s%-20s%-20s'%('supplier name','software name','amount'))
-for left padding and +ve(default) for right padding
Related
I am trying to use a text widget in tkinter to display the output of my code.
sequence = ("This peptide contains ", len(Peptide), "total residues", "\n")
text.insert("current", sequence)
this seems to work, except for that when it is printed, the
elements are separated by {}.
I would prefer for the output to not have these parenthesis, and read like: "This peptide contains 17 total residues". Is there a way to do this?
Thank you
It is because sequence is a tuple. Try changing it to
sequence = "This peptide contains {} total residues\n".format(len(Peptide))
I have a dictionary data that I need to write it into a CSV file under the heading Form Name Type & Definition, the dictionary data to write is in the code snippet below.
writeData.py
def writeCSV():
# Dictionary Data to write received from Form Submit
csvData = {
'form' : 'Customer',
'Customer [form]' : 'Customer is module for recording information related to customer such as Name, Address, Date of Birth, Place of Birth, ID Number, etc.',
'Salutation [label]' : 'A greeting in words or actions, or the words used at the beginning of a letter or speech. This field has values such as Mr, Ms, Miss.',
'First Name English [label]': 'The name that was given to you when you were born and that comes before your family name. This field accept only English Character.'
}
items = {key:value for key,value in csvData.iteritems() if key != 'form'}
form = csvData.get('form')
Columns = ['Form','Name','Type','Definition']
string = ''
with open("myfile.csv","w+") as f:
# Write Heading
for col_header in Columns:
string = string + "," + col_header
f.write(string[1:]+'\n')
# Write Data Body
string = ''
for key,value in items.iteritems():
string = form + "," + key + "," + " " + ","+value
f.write(string)
f.write('\n')
return ''
writeCSV()
However, after I executed the python script above, data was written correctly under the heading Form, Name, and Type. Yet, under the heading Definition, the data was expanded to some more column be young its heading Definition.
I searched around but no clue why it expands column like this, or the amount of data is limited inside on csv column? What's wrong with this, how can I write its data in correct column of CSV file? Thanks.
The problem is that csv delimiter each column by a special character. In your case, you are using a comma ','. But in your text also commas occur. So the csv takes this as a delimiter and interprets it as a new column. You can switch from comma to semicolon ';' as a delimiter. But even then you have to ensure that there are no semicolons in your original text.
If you make it this way you need to change these lines:
string = string + ";" + col_header # ; instead of ,
string = form + ";" + key + ";" + " " + ";"+value
But I would suggest using a library, like #Nathaniel suggests
You may have success converting your dictionary to a data frame and then saving it to a csv:
import pandas as pd
csvData = {'form' : 'Customer',
'Customer [form]' : 'Customer is module for recording information related to customer such as Name, Address, Date of Birth, Place of Birth, ID Number, etc.',
'Salutation [label]' : 'A greeting in words or actions, or the words used at the beginning of a letter or speech. This field has values such as Mr, Ms, Miss.',
'First Name English [label]': 'The name that was given to you when you were born and that comes before your family name. This field accept only English Character.'
}
# Try either of these
df = pd.DataFrame(csvData, index=[0])
#df = pd.DataFrame.from_dict(csvData)
# Output to csv
df.to_csv('myfile.csv')
Without some example data, it is difficult to test this on your data.
It did not expand into adjacent columns; because of the size of the text, it doesn't fit the column width, and Excel's default is to draw that text over adjacent columns. You can verify this is the case by selecting cells that it appears to have expanded into, and seeing they are in fact empty. You can also change the way these cells are displayed, "wrapping" their contents within the column provided (making the rows taller).
Using this code I was able to cycle through several instances of attributes and extract First and Last name if they matched the criteria. The results are a list of dict. How would i make all of these results which match the criteria, return as a full name each on it's own line as text?
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
print({players['firstName'], players['lastName']})
Results of Print Statement
{'Chandon', 'Sullivan'}
{'Urban', 'Brent'}
Are you looking for this:
print(players['firstName'], players['lastName'])
This would output:
Chandon Sullivan
Urban Brent
Your original trial just put the items to a set {}, and then printed the set, for no apparent reason.
Edit:
You can also for example join the firstName and lastName to be one string and then append the combos to a lists. Then you can do whatever you need with the list:
names = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
names.append(f"{players['firstName']} {players['lastName']}")
If you're using a version of Python lower than 3.6 and can't use f-strings you can do the last line for example like this:
names.append("{} {}").format(players['firstName'], players['lastName'])
Or if you prefer:
names.append(players['firstName'] + ' ' + players['lastName'])
Ok I figured out by appending the first and last name and creating a list for the found criteria. I then converted the list to a string to display it on the device.
full_list = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
full_list.append((players['firstName'] + " " + players['lastName']))
send_message('\n'.join(str(i) for i in full_list))
I'm making a program in school where users are quizzed on certain topics and their results are saved into a csv file. I've managed to print off the row with the highest score, but this doesn't look very neat.
with open ('reportForFergusTwo.csv', 'r') as highScore:
highScoreFinder=highScore
valid3=False
for row in highScoreFinder:
if subjectInput in row:
if difficultyInput in row:
if ('10' or '9' or '8' or '7' or '6' or '5' or '4' or '3' or '2' or '1') in row:
valid3=True
print("The highest score for this quiz is:",row)
For example: it says, "The highest score for this quiz is: chemistry,easy,10,Luc16" but I would prefer it to say something like "The highest score for this quiz is: 10" and "This score was achieved by: Luc16", rather than just printing the whole row off, with unnecessary details like what the quiz was on.
My CSV file looks like this:
Subject,Difficulty,Score,Username
language,easy,10,Luc16
chemistry,easy,10,Luc16
maths,easy,9,Luc16
chemistry,easy,5,Eri15
chemistry,easy,6,Waf1
chemistry,easy,0,Eri15
I thought that maybe if I could find a way to take the individual results (the score and username) and put them into their own individual variables, then it would be much easier to present it the way I want, and be able to reference them later on in the function if I need them to be displayed again.
I'm just fairly new to coding and curious if this can be done, so I can improve the appearance of my code.
Edit: To solve the issue, I used str.split() to break up the indivudal fields in the rows of my CSV, so that they could be selected and held by a variable. The accepted answer shows the solution I used, but this is my final code in case this wasn't clear
with open ('details.csv', 'r') as stalking:
stalkingReader=csv.reader(stalking)
valid4=False
for column in stalkingReader:
if user in column[3]:
valid4=True
print("Here are the details for user {}... ".format(user))
splitter=row.split(',')
name=splitter[0]
age=splitter[1]
year=splitter[2]
print("Name: {}".format(name))
print("Age: {}".format(age))
print("Year Group: {}".format(year))
postReport()
if valid4==False:
print("Sorry Fergus, this user doesn't seem to be in our records.")
with open("reportForFergusTwo.csv", "r") as highScore:
subject = []
difficulty = []
score = []
name = []
for line in highScore:
subject.append(line.split(',')[0])
difficulty.append(line.split(',')[1])
score.append(line.split(',')[2])
name.append(line.split(',')[3])
ind = score.index(max(score)
print("The highest score for this quiz is: ", max(score))
print("This was achieved by ", name[ind])
with opens (and will close) the .csv file.
Then, four empty lists are created.
Next, I loop through every line in the file, and I split every line using a comma as the delimiter. This produces a list of four elements, which are appended to each list.
You can use str.split() to break up the rows of your CSV so that you can individually reference the fields:
split_row = row.split(',')
score = split_row[2]
user = split_row[3]
print("The highest score for this quiz is: " + score)
print("This score was achieved by: " + user)
You can use csv library
import csv
with open("data", "r") as f:
reader = csv.reader(f)
# skip header
reader.next()
# organize data in 2D array
data = [ [ sub, dif, int(score), name ] for sub, dif, score, name in reader ]
# sort by score
data.sort(key=lambda x: x[2], reverse=True)
# pretty print
print "The highest score for this quiz is:", data[0][2]
print "This score was achieved by:", data[0][3]
(Posted solution on behalf of the OP).
To solve the issue, I used str.split() to break up the indivudal fields in the rows of my CSV, so that they could be selected and held by a variable. The accepted answer shows the solution I used, but this is my final code in case this wasn't clear
with open ('details.csv', 'r') as stalking:
stalkingReader=csv.reader(stalking)
valid4=False
for column in stalkingReader:
if user in column[3]:
valid4=True
print("Here are the details for user {}... ".format(user))
splitter=row.split(',')
name=splitter[0]
age=splitter[1]
year=splitter[2]
print("Name: {}".format(name))
print("Age: {}".format(age))
print("Year Group: {}".format(year))
postReport()
if valid4==False:
print("Sorry Fergus, this user doesn't seem to be in our records.")
the text file looks like: textabbrv.txt
r:are
u:you
ttyl:talk to you later
l8:late
brb:be right back
i tried a lot to fix this, but there is one error, my program is:
def main():
indexEntries={}
infile=open('textabbrv.txt','r')
fields=extractRecord(infile)
while len(fields)>0:
set_entries(indexEntries,fields[1],fields[0])
fields=extractRecord(infile)
infile.close()
printIndex(indexEntries)
def extractRecord(infile):
line=infile.readline()
if line!="":
fields=line.split(":")
page=fields[0].rstrip()
term=fields[1].rstrip()
return [page,term]
else:
return []
def set_entries(entries,term,page):
pageSet=set([page])
entries[term]=pageSet
def printIndex(entries):
user_input=input("Enter a message to be translated: \n")
if user_input!=" ":
user_split=user_input.replace(","," ").replace("?"," ").replace("!"," ").\
replace(":"," ").replace(";"," ").split(" ")
print()
print("The translated text is: ")
for long_form in entries:
sentence=entries[long_form]
for short_form in sentence:
if short_form in user_split:
print(user_input.replace(short_form,long_form))
main()
OUTPUT:
Enter a message to be translated:
ttyl,brb
The translated text is:
talk to you later,brb
ttyl,be right back
but the output should look like this and should be translated in just one line, i think i messed up somewhere in the for loops a the end of the program
Enter a message to be translated:
ttyl,brb
The translated text is:
talk to you later,be right back
First of all, the output you see is due to this:
print(user_input.replace(short_form,long_form))
Whenever you find a match, you replace that match in the original user input, and print it out, but you don't store that modified version of the original input at all.
You could fix that by doing:
user_input = user_input.replace(short_form,long_form)
and then printing the new version of user_input at the end of printIndex. Now, that may be problematic, but that's another story.
In any case... the way you have approached this is a bit unusual. You are populating the indexEntries dictionary in the reverse way that I would expect. You put the indices as the values! Instead:
1) I would import csv and rewrite this:
infile=open('textabbrv.txt','r')
fields=extractRecord(infile)
while len(fields)>0:
set_entries(indexEntries,fields[1],fields[0])
fields=extractRecord(infile)
infile.close()
as:
with open('textabbrv.txt','r') as infile:
for (field1, field2) in csv.reader(infile, delimiter=':'):
indexEntries[field1] = field2
In the process I'm getting rid of extractRecord and set_entries. Now the dictionary looks like {'brb': 'be right back', 'r': 'are, ...}
2) You're splitting the user input, but then you don't make use of that. Let's rewrite this:
for long_form in entries:
sentence=entries[long_form]
for short_form in sentence:
if short_form in user_split:
print(user_input.replace(short_form,long_form))
and make it:
output = []
for word in user_split:
# The following could be written as
# output.append(entries.get(word, word))
if word in entries:
output.append(entries[word])
else:
output.append(word)
print ','.join(output)