Shoveling objects into an array - arrays

I'm working on scraping.
class MMA::School
attr_accessor :name, :location_info, :url
def self.today
self.schools
end
def self.schools
schools = []
schools << self.scrape_cbs
schools
end
def self.scrape_cbs
doc = Nokogiri::HTML(open("http://newyork.cbslocal.com/top-lists/5-best-mma-and-martial-arts-studios-in-new-york/"))
schools_1 = self.new
schools_1.name = doc.search("//div/p/strong/span").text.strip
schools_1.location_info = doc.search("//div/p")[4].text.strip
schools_1.url = doc.search("//div/p/a")[0].text.strip
schools_1
schools_2 = self.new
schools_2.name = doc.search("//div/p/span")[0].text.strip
schools_2.location_info = doc.search("//div/p")[7].text.strip
schools_2.url = doc.search("//div/p/a")[2].text.strip
schools_2
schools_3 = self.new
schools_3.name = doc.search("//div/p/span")[1].text.strip
schools_3.location_info = doc.search("//div/p")[9].text.strip
schools_3.url = doc.search("//div/p/a")[3].text.strip
schools_3
schools_4 = self.new
schools_4.name = doc.search("//div/p/span")[2].text.strip
schools_4.location_info = doc.search("//div/p")[12].text.strip
schools_4.url = doc.search("//div/p/a")[5].text.strip
schools_4
schools_5 = self.new
schools_5.name = doc.search("//div/p/span")[3].text.strip
schools_5.location_info = doc.search("//div/p")[14].text.strip
schools_5.url = doc.search("//div/p/a")[6].text.strip
schools_5
end
end
I have some trouble placing my scraped data into an empty array. It only pushes one of the schools_1 etc. to the schools array.
Does anyone have any suggestions on how to fix this?

Without any explanation, it is absolutely not clear what you are trying to do, but it is clear that in your self.scrape_cbs definition, the lines:
schools_1
...
schools_2
...
...
schools_4
are meaningless. Perhaps, you intended to return an array like this from this method:
[schools_1, schools_2, ..., schools_5]
If so, put the line above as the last line of your method definition of self.scrape_cbs.

Related

Add M2M field using create(): Django

I have a lot of doubts about managing the M2m field, I finally got a solution to add that data to a model, but there are still some issues, give me a solution to overcome this,
class CourseListSerializer(serializers.ModelSerializer):
instructors = serializers.SerializerMethodField()
image = FileField()
keyarea = CourseKeyAreaSerializer
subject = CourseSubjectsSerializer
sections = serializers.ListField(write_only=True)
beneficiaries = serializers.ListField(write_only=True)
section = CourseSectionSerializers
beneficiary = CourseBeneficiarySerializer
def create(self, validated_data):
data = validated_data
try:
new = Course.objects.create(image=data['image'], name=data['name'], description=data['description'], is_free=data['is_free'],
keyarea=data['keyarea'], subject=data['subject'])
new.save()
beneficiary_data = data['beneficiaries']
new.beneficiary.set(*[beneficiary_data])
section_data = data['sections']
new.section.set(*[section_data])
return new
except Exception as e:
e = "invalid data"
return e
here first creating the "new" object after that to set the M2M field like
"new.beneficiary.set(*[beneficiary_data])"
but is there any way to add beneficiary and section like this
"new = Course.objects.create(image=data['image'],name=data['name'], description=data['description'],is_free=data['is_free'],....)"

Adding the letters of the alphabet to the string in order

I have a alphabet, like: ABCDEFGHILJKLMN
And i have a string like: https://test.com/c={here}
I want to add the above letters to the end of this string, respectively, where it says here.
Example:
https://test.com/c=A
https://test.com/c=B
https://test.com/c=C
I wrote a code like this:
class GetNames():
def __init__(self):
self.url = "https://test.com/c="
self.new_url = []
self.letters = ['A','B','C','Ç','D','E','F','G','H','I','İ','J','K','L','M','N','O',
'Ö','P','R','S','T','Ş','U','Ü','V','Y','Z']
def get_letter(self):
index = 0
while self.letters:
self.url += self.letters[index]
self.new_url.append(self.url)
index += 1
if index == 28:
break
print(self.new_url)
I get output like this:
https://test.com/c=A
https://test.com/c=AB
https://test.com/c=ABC
How can i fix this ?
insert this line add the first of while loop like below:
self.url = "https://test.com/c="
finally code:
class GetNames():
def __init__(self):
self.url = "https://test.com/c="
self.new_url = []
self.letters = ['A','B','C','Ç','D','E','F','G','H','I','İ','J','K','L','M','N','O',
'Ö','P','R','S','T','Ş','U','Ü','V','Y','Z']
def get_letter(self):
index = 0
while self.letters:
self.url = "https://test.com/c="
self.url += self.letters[index]
self.new_url.append(self.url)
index += 1
if index == 28:
break
print(self.new_url)
output:
['https://test.com/c=A', 'https://test.com/c=B', 'https://test.com/c=C', ...
After self.url += self.letters[index]
self.new_url.append(self.url)
make sure to add this line: self.url="https://test.com/c="
Your code looks complicated, you can use for loops instead of while
class GetNames:
def __init__(self):
self.url = 'http://test.com/c='
self.new_url = []
self.letters = ['A','B','C','Ç','D','E','F','G','H','I','İ','J','K','L','M','N','O',
'Ö','P','R','S','T','Ş','U','Ü','V','Y','Z']
def get_letter(self):
for i in range(28):
self.new_url.append(self.url + self.letters[i])
a = GetNames()
a.get_letter()
print(a.new_url)
Output
['http://test.com/c=A', 'http://test.com/c=B', ... , 'http://test.com/c=Y', 'http://test.com/c=Z']

Assign Array Position to a Label Tag Property

I want to assign an array to the Tag property of 16 Labels. This is what I came up with:
Label1.Tag = FotoArray(0)
Label2.Tag = FotoArray(1)
Label3.Tag = FotoArray(2)
Label4.Tag = FotoArray(3)
Label5.Tag = FotoArray(4)
Label6.Tag = FotoArray(5)
Label7.Tag = FotoArray(6)
Label8.Tag = FotoArray(7)
Label9.Tag = FotoArray(8)
Label10.Tag = FotoArray(9)
Label11.Tag = FotoArray(10)
Label12.Tag = FotoArray(11)
Label16.Tag = FotoArray(12)
Label13.Tag = FotoArray(13)
Label15.Tag = FotoArray(14)
Label14.Tag = FotoArray(15)
Is there a way to do it in a shorter way?
Assuming Label16.Tag = FotoArray(12) is a typo, this should do the work:
For counter As Integer = 1 To 16
Dim label As Label = Me.Controls.Find("Label" & counter, True).FirstOrDefault()
If Not label Is Nothing Then
label.Tag = FotoArray(counter - 1)
End If
Next
You can also simply use Me.Controls(name) instead. The updated code would look like this:
For counter As Integer = 1 To 16
Dim label As Label = Me.Controls("Label" & counter)
If Not label Is Nothing Then
label.Tag = FotoArray(counter - 1)
End If
Next

Returning a dictionary from a file

I have have written this code defining a class
class OrderRecord:
"""Defines an OrderRecord class, suitable for use in keeping track of order records"""
import tools2
def __init__(self, string):
"""Creates a new OrderRecord object"""
string = string.split(',')
self.date = string[0]
self.location = string[1]
self.name = string[2]
self.colour = string[3]
self.order_num = string[4]
self.cost = 0
def cost_of_order(self):
"""Creates a list of the name and adds up the cost of each letter"""
letter = list(self.name)
for let in letter:
self.cost = self.cost + self.tools2.letter_price(let, self.colour)
return self.cost
def __str__(self):
"""Calls the cost_of_order function and returns the split string in the required format"""
self.cost = self.cost_of_order()
return("Date: {0}\nLocation: {1}\nName: {2}\nColour: \
{3}\nOrder Num: {4}\nCost: {5:.2f}".format(self.date, self.location, \
self.name, self.colour, self.order_num, self.cost))
Now I need to write a function that reads a file containing the following:
20130902,Te Rakipaewhenua,Vinas,parauri,8638
20130909,Te Papaioea,McClary,kikorangi,11643
20131215,Kapiti,Labrie,kikorangi,65291
20141106,Waihopai,Labrie,ma,57910
and returns a dictionary that has the location as the key and lists of OrderRecords as the values.
I know this isn't too hard of a task but I have been stuck on this for awhile because I can't get my head around what to do for it.
Any help would be appreciated.
Maybe something like this. It is not the solution but it has what you need with some modifications.
import collections
dct_result = collections.defaultdict(list)
for line in open('file_path'):
fields = line.split(',')
# index 1 being the second column
dct_result[field(1)].append(OrderRecord( some args ))

How to create a nested dictionary from a datastore model?

I am working on this problem a couple of days, my idea is from this model:
class oceni(db.Model):
user = db.UserProperty()
weight = db.FloatProperty()
item = db.StringProperty()
..to create a dictionary in this format:
collection = dict()
collection = {
'user1':{'item1':weight1,'item2':weight2..},
'user2':{'item3':weight3,'item4':weight4..},
..}
..and as far as I reached is this:
kontenier = db.GqlQuery('SELECT * FROM oceni')
kolekcija = dict()
tmp = dict()
lista = []
for it in kontenier:
lista.append(it.user)
set = []
for e in lista:
if e not in set:
set.append(e)
for i in set:
kontenier = db.GqlQuery('SELECT * FROM oceni WHERE user=:1',i)
for it in kontenier:
tmp[it.item]=it.weight
kolekcija[i]=tmp
..but this creates a dictionary where all the users have the same dictionary with items and their weight. I know this isn't the most pythonic way, but I'm new to this so I will be eager to learn something more about this problem.
I've used your variable names your notation in this snippet.
kontenier = db.GqlQuery('SELECT * FROM oceni')
kolekcija = {}
for it in kontenier:
if it.user not in kolekcija:
kolekcija[it.user] = {}
kolekcija[it.user][it.item] = it.weight

Resources