Just studying data structures in python for a project and can't work out the difference in a dictionary and a data structures in this form:
class Address:
def __init__(self, house_number, house_street, house_city,
house_county, house_postcode):
self.number = house_number
self.street = house_street
self.city = house_city
self.county = house_county
self.postcode = house_postcode
def __repr__(self):
return ('<Class: \'Address\', '+ str(self.number) + ' ' +
self.street + ' ' + self.city + ' ' +
self.county + ' ' + self.postcode + '>')
## Creates an object Address and assign it to a variable
my_address = Address(1, 'abc', 'def', 'ghi', 'jkl')
## Print the object My_address
print 'Address object:', my_address
print 'house number:', my_address.number
## change house number
my_address.number = 555
print 'NEW house number:', my_address.number
The code sample is modified from sample code given in a lecture at university of york.
A python dict is a highly optimized hash table, which is a data structure.
So, to put it differently, a python dict is one example of a data structure. So are the set, list, string and unicode types. A custom class is again another data structure, one that is highly customizable to your application needs.
From the WikiPedia entry on Data structure:
In computer science, a data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.
Data structures in python can have the form of lists,dictionaries,even for emtpy classes that just use the pass keyword.They are like the struct in C.
They are those objects that can actually store some data in some order or not.
Related
I am doing a university assignment and since we are excluded from using any web scrapping libraries, I am limited to regex, I have the current code written (excuse the poor formatting, I am still very new):
def print_ticket():
if event.get() == 1:
web_page = urlopen(url1)
html_code = web_page.read().decode("UTF-8")
web_page.close()
event_title = findall('<h6.*>(.+)</h6>', html_code)[0]
event_image = findall('<img.* src="([^"]+)".*>', html_code)[4]
event_url = 'https://suncorpstadium.com.au/what-s-on.aspx'
event_details = findall('<h7.*>(.+)</h7>', html_code)[1]
filename = event_title.replace(' ', '_') + '_Ticket.html'
html_file = open(filename, 'w')
html_file.write(ticket_template.replace('EVENT TITLE', event_title + ' Ticket'))
html_file.write(ticket_template.replace('IMAGE', event_image))
html_file.write(ticket_template.replace('DATE TIME', event_details))
My issue is, everytime I run that that event in my GUI, my web document prints 3 different sets of my template with the .write replaces occurring on one per section.
Is there a way to make multiple .replaces at once without it printing multiple copies of my template?
The problem is that you are calling write 3 times and you need to call it just once. So what you could do:
ticket_template = ticket_template.replace('EVENT TITLE', event_title + ' Ticket')
ticket_template = ticket_template.replace('IMAGE', event_image)
ticket_template = ticket_template.replace('DATE TIME', event_details)
html_file.write(ticket_template)
in that way it will work, and you will only have the final output of the ticket_template. Also you can reduce this to a one-liner but it won't look legible
html_file.write(ticket_template.replace('EVENT TITLE', event_title + ' Ticket').replace('IMAGE', event_image).replace('DATE TIME', event_details))
You can do it using an "f-string" or Formatted string literal which was introduced in Python 3.6. To control its evaluation, it must be specified as the result returned from a lambda function as shown in the sample code below.
Note that the variable names used do not have to be ALL_CAPS as shown — I only did it that way to make it easier to spot where they're being used.
ticket_template = lambda: f'''\
Congratulations! Your ticket to {EVENT_TITLE} has been booked!
{IMAGE}
{DATE} {TIME}
'''
filename = 'whatever.html'
with open(filename, 'w') as html_file:
EVENT_TITLE = 'Some event title'
IMAGE = 'Picture of event'
DATE, TIME = '29/05', '4:00 PM'
filled_in_ticket = ticket_template() # *Call* the lambda function.
html_file.write(filled_in_ticket)
print('fini')
I got a list in Python with Twitter user information and exported it with Pandas to an Excel file.
One row is one Twitter user with nearly all information of the user (name, #-tag, location etc.)
Here is my code to create the list and fill it with the user data:
def get_usernames(userids, api):
fullusers = []
u_count = len(userids)
try:
for i in range(int(u_count/100) + 1):
end_loc = min((i + 1) * 100, u_count)
fullusers.extend(
api.lookup_users(user_ids=userids[i * 100:end_loc])
)
print('\n' + 'Done! We found ' + str(len(fullusers)) + ' follower in total for this account.' + '\n')
return fullusers
except:
import traceback
traceback.print_exc()
print ('Something went wrong, quitting...')
The only problem is that every row is in JSON object and therefore one long comma-seperated string. I would like to create headers (no problem with Pandas) and only write parts of the string (i.e. ID or name) to colums.
Here is an example of a row from my output.xlsx:
User(_api=<tweepy.api.API object at 0x16898928>, _json={'id': 12345, 'id_str': '12345', 'name': 'Jane Doe', 'screen_name': 'jdoe', 'location': 'Nirvana, NI', 'description': 'Just some random descrition')
I have two ideas, but I don't know how to realize them due to my lack of skills and experience with Python.
Create a loop which saves certain parts ('id','name' etc.) from the JSON-string in colums.
Cut off the User(_api=<tweepy.api. API object at 0x16898928>, _json={ at the beginning and ) at the end, so that I may export they file as CSV.
Could anyone help me out with one of my two solutions or suggest a "simple" way to do this?
fyi: I want to do this to gather data for my thesis.
Try the python json library:
import json
jsonstring = "{'id': 12345, 'id_str': '12345', 'name': 'Jane Doe', 'screen_name': 'jdoe', 'location': 'Nirvana, NI', 'description': 'Just some random descrition')"
jsondict = json.loads(jsonstring)
# type(jsondict) == dictionary
Now you can just extract the data you want from it:
id = jsondict["id"]
name = jsondict["name"]
newdict = {"id":id,"name":name}
I'm super new to Python and just trying my hand at a random email generator.
I'm just using json files with datasets in them, so there may be a better way to do this.
I can get the script to work no problems, but I need some advice on something. I want the senders email to be the same as the sign off name.
I.E. david_jones#hotmail etc comes from Regards, David Jones. At the moment i've got it generating a separate random email, and separate sign off name. I need to link the two. Everything else is ok at the moment.
Can anyone help me with a better way to do this?
Code:
import json
import random
f = open("C:/Users/*/Desktop/Email.txt", "a")
sentfrom = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Send.json').read())
send = sentfrom [random.randint(0,4)]
carboncopy = "CC:"
receiver = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/To.json').read())
to = receiver[random.randint(0,4)]
datesent = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Date.json').read())
date = datesent[random.randint(0,4)]
subjects = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Subject.json').read())
subject = subjects[random.randint(0,4)]
greetings = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Greeting.json').read())
greeting= greetings[random.randint(0,4)]
firstsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent1.json').read())
sent1 = firstsentence[random.randint(0,4)]
secondsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent2.json').read())
sent2 = secondsentence[random.randint(0,4)]
thirdsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent3.json').read())
sent3 = thirdsentence[random.randint(0,4)]
fourthsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent4.json').read())
sent4 = fourthsentence[random.randint(0,4)]
farewell = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Goodbye.json').read())
goodbye = farewell[random.randint(0,4)]
regards = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sender.json').read())
salutation = regards[random.randint(0,4)]
conversation = send +'\n'+ to +'\n'+ carboncopy +'\n'+ date +'\n'+ subject +'\n'+ '\n' + greeting +', \n'+ '\n' + sent1 +'\n'+ '\n' + sent2 +'\n'+'\n'+ sent3 +'\n'+'\n'+ sent4 +'\n'+'\n'+ goodbye +'\n'+'\n'+ salutation
f.write(conversation)
f.close()
Thanks in advance,
Buzz
Assuming that regards is what contains the sign off name..
You want to first get rid of the sign off name, instead of 'Regards, John Doe', Have all of them be 'Regards', 'Best', 'Thanks!' etc. maybe just create a list instead of reading it from json:
regards = ['Regards,', 'Best,', 'Thanks!' ...]
Assuming everyone's format in email is the same, i.e. john_doe#whatever.com, you can get the name from this:
my_name = to.split('#')[0].replace('_', ' ').title()
# my_name will be 'John Doe'
And then add my_name to the conversation after salutation.
I was trying to split combination of string, unicode in python. The split has to be made on the ResultSet object retrieved from web-site. Using the code below, I am able to get the details, actually it is user details:
from bs4 import BeautifulSoup
import urllib2
import re
url = "http://www.mouthshut.com/vinay_beriwal"
profile_user = urllib2.urlopen(url)
profile_soup = BeautifulSoup(profile_user.read())
usr_dtls = profile_soup.find("div",id=re.compile("_divAboutMe")).find_all('p')
for dt in usr_dtls:
usr_dtls = " ".join(dt.text.split())
print(usr_dtls)
The output is as below:
i love yellow..
Name: Vinay Beriwal
Age: 39 years
Hometown: New Delhi, India
Country: India
Member since: Feb 11, 2016
What I need is to create distinct 5 variables as Name, Age, Hometown, Country, Member since and store the corresponding value after ':' for same.
Thanks
You can use a dictionary to store name-value pairs.For example -
my_dict = {"Name":"Vinay","Age":21}
In my_dict, Name and Age are the keys of the dictionary, you can access values like this -
print (my_dict["Name"]) #This will print Vinay
Also, it's nice and better to use complete words for variable names.
results = profile_soup.find("div",id=re.compile("_divAboutMe")).find_all('p')
user_data={} #dictionary initialization
for result in results:
result = " ".join(result.text.split())
try:
var,value = result.strip().split(':')
user_data[var.strip()]=value.strip()
except:
pass
#If you print the user_data now
print (user_data)
'''
This is what it'll print
{'Age': ' 39 years', 'Country': ' India', 'Hometown': 'New Delhi, India', 'Name': 'Vinay Beriwal', 'Member since': 'Feb 11, 2016'}
'''
You can use a dictionary to store your data:
my_dict = {}
for dt in usr_dtls:
item = " ".join(dt.text.split())
try:
if ':' in item:
k, v = item.split(':')
my_dict[k.strip()] = v.strip()
except:
pass
Note: You should not use usr_dtls inside your for loop, because that's would override your original usr_dtls
This question already has answers here:
How can I print multiple things (fixed text and/or variable values) on the same line, all at once?
(13 answers)
Closed 9 months ago.
So for my first project it is a simple program that prints your name class you are in and what high school you went to. The one thing that is messing me up is for one of them I have to use one print() statement for all this and I need to format it so that each piece of information is on a different line.
What I want for the format:
first_name, last_name
course_id, course_name, email
school
But what I get is
first_name, last_name
course_id, course_name, email
school
How do I remove the space?
My code is as follows:
first_name = 'Daniel'
last_name = 'Rust'
course_id = 'Csci 160'
course_name = 'Computer Science 160'
email = 'blah#gmail.com'
school= 'Red River Highschool'
#variables printed for B
print(first_name, last_name, '\n', course_id, course_name, email, '\n', school, '\n')
print inserts a space between each argument. You can disable this by adding , sep='' after the last '\n', but then there won't be any spaces between first_name and last_name or between course_id and course_name, etc. You could then go on to insert , ' ' manually where you need it in the print statement, but by that point it might be simpler to just give print a single argument formed by concatenating the strings together with explicit spaces:
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name
+ ' ' email + '\n' + school + '\n')
As mentioned here, you can use the sep='' argument to the print() function. That will let you set the separator between printed values (which is a space by default) to whatever you want, including an empty string. You'll have to remember to add spaces between the values that you do want separated. E.g.,
print(first_name, ' ', last_name, '\n', course_id, [...], sep='')
There's a better way to do this, involving the format() method on strings, but your professor is probably saving that one for the next lesson so I won't cover it in detail now. Follow the link to the Python docs, and read the section on Format String Syntax, if you want more details. I'll just show you an example of what your code would look like using format():
print("{} {}\n{} {} {}\n{}".format(first_name, last_name, course_id, course_name, email, school))
Note no \n at the end, since print() automatically adds a newline unless you tell it otherwise.
I recommend reading through str.format() to print your information.
The spaces in your output come from the fact that you've called the print function, passing a list of strings, instead of passing the print function a single string.
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name + ' ' + email + '\n' + school)
yields
Daniel Rust
Csci 160 Computer Science 160 blah#gmail.com
Red River Highschool
Just don't add space in your code
print(first_name, last_name, '\n',course_id, course_name, email, '\n', school, '\n')
There are a number of ways to do so.
First can be str.format() as
print ('{} {}\n{} {} {}\n{}'.format(first_name, last_name, course_id, course_name, email, school))
Second can be
print (first_name, ' ', last_name, '\n',course_id, ' ', course_name, ' ', email, '\n',school, sep = '')
And the third can be
print (first_name + ' ' + last_name + '\n' + str(course_id) + ' ' + course_name + ' ' + email + '\n' + school)
Simple multiline print in python using f-string,
first_name = 'Daniel'
last_name = 'Rust'
course_id = 'Csci 160'
course_name = 'Computer Science 160'
email = 'blah#gmail.com'
school= 'Red River Highschool'
#variables printed for B
print(first_name, last_name, '\n', course_id, course_name, email, '\n', school, '\n')
print(f'''
{first_name}, {last_name}
{course_id}, {course_name}, {email}
{school}''')
Daniel Rust
Csci 160 Computer Science 160 blah#gmail.com
Red River Highschool
Daniel, Rust
Csci 160, Computer Science 160, blah#gmail.com
Red River Highschool
[Program finished]
How to print several lines by using one print statement and how to add new line?
pi = 3.14159 # approximate
diameter = 3
radius = diameter/2
area = pi * radius * radius
circumference = 2 * pi * radius
print("{}\n{}\n{}\n".format(area,radius,circumference))
output::
7.068577499999999
1.5
9.424769999999999
the above you will get corrcet answer for this code.