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']
Related
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.
I got this problem. I have a
val line:String = "PE018201804527901"
that matches with this
regex : (.{2})(.{4})(.{9})(.{2})
I need to extract each group from the regex to an Array.
The result would be:
Array["PE", "0182","018045279","01"]
I try to do this regex:
val regex = """(.{2})(.{4})(.{9})(.{2})""".r
val x= regex.findAllIn(line).toArray
but it doesn't work!
regex.findAllIn(line).subgroups.toArray
Note that findAllIn does not automatically anchor the regex pattern, and will find a match inside a much longer string. If you need to only allow matches inside 17 char strings, you can use a match block like this:
val line = "PE018201804527901"
val regex = """(.{2})(.{4})(.{9})(.{2})""".r
val results = line match {
case regex(g1, g2, g3, g4) => Array(g1, g2, g3, g4)
case _ => Array[String]()
}
// Demo printing
results.foreach { m =>
println(m)
}
// PE
// 0182
// 018045279
// 01
See a Scala demo.
It also handles no match scenario well initializing an empty string array.
If you need to get all matches and all groups, then you will need to grab the groups into a list and then add the list to a list buffer (scala.collection.mutable.ListBuffer):
val line = "PE018201804527901%E018201804527901"
val regex = """(.{2})(.{4})(.{9})(.{2})""".r
val results = ListBuffer[List[String]]()
val mi = regex.findAllIn(line)
while (mi.hasNext) {
val d = mi.next
results += List(mi.group(1), mi.group(2), mi.group(3), mi.group(4))
}
// Demo printing
results.foreach { m =>
println("------")
println(m)
m.foreach { l => println(l) }
}
Results:
------
List(PE, 0182, 018045279, 01)
PE
0182
018045279
01
------
List(%E, 0182, 018045279, 01)
%E
0182
018045279
01
See this Scala demo
Your solution #sheunis was very helpful, finally I resolved it with this method:
def extractFromRegex (regex: Regex, line:String): Array[String] = {
val list = ListBuffer[String]()
for(m <- regex.findAllIn(line).matchData;
e <- m.subgroups)
list+=e
list.toArray
}
Because your solution with this code:
val line:String = """PE0182"""
val regex ="""(.{2})(.{4})""".r
val t = regex.findAllIn(line).subgroups.toArray
Shows the next exception:
Exception in thread "main" java.lang.IllegalStateException: No match available
at java.util.regex.Matcher.start(Matcher.java:372)
at scala.util.matching.Regex$MatchIterator.start(Regex.scala:696)
at scala.util.matching.Regex$MatchData$class.group(Regex.scala:549)
at scala.util.matching.Regex$MatchIterator.group(Regex.scala:671)
at scala.util.matching.Regex$MatchData$$anonfun$subgroups$1.apply(Regex.scala:553)
at scala.util.matching.Regex$MatchData$$anonfun$subgroups$1.apply(Regex.scala:553)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
at scala.collection.AbstractTraversable.map(Traversable.scala:105)
at scala.util.matching.Regex$MatchData$class.subgroups(Regex.scala:553)
at scala.util.matching.Regex$MatchIterator.subgroups(Regex.scala:671)
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 ))
I'd like to create a container class for objects based on a Ruby array. I'd like to manipulate more than one of these containers, like concatenating 2 together. If I try this:
class Thing
attr_accessor :name
end
class Things
def initialize
#things = Array.new
end
def addone( a )
#things.push( a )
end
def append( list )
list.each { |i| addone( i ) }
end
end
item1 = Thing.new
item2 = Thing.new
item3 = Thing.new
item4 = Thing.new
item1.name = "Marty"
item2.name = "Fred"
item3.name = "Janice"
item4.name = "John"
list1 = Things.new
list1.addone( item1 )
list1.addone( item2 )
list2 = Things.new
list2.addone( item3 )
list2.addone( item4 )
list3 = Things.new
list3 = list2.append( list1 )
I get the error:
in append': undefined methodeach' for # (NoMethodError) from ./test.rb:40:in `'
I've tried different approaches, for example creating an each method as it seems to want, but no luck so far. Any suggestions? And thanks in advance!
If you want to be able to add Things to Things, you have two abilities: either to implement iterator methods on Things or simply decorate wrapped Array:
def append(list)
case list
when Enumerable then list.each { |i| addone(i) }
when Things then list.instance_variable_get(:#things).each { |e| addone(i) }
else raise "Sorry, can’t add #{list}"
end
I guess there should be a getter/setter methods:
attr_accessor :things
Then you should change your addone method:
def append(list)
list.things.each { |i| addone( i ) } # iterate through array items, not Things instance object
self # return appended list object instead of unchanged provided argument – list1
end
Output of list3.things:
=> [#<Context::Thing:0x00000001adea48 #name="Janice">,
#<Context::Thing:0x00000001ade9f8 #name="John">,
#<Context::Thing:0x00000001adea98 #name="Marty">,
#<Context::Thing:0x00000001adea70 #name="Fred">]
Demonstration
Consider this approach:
class Thing
attr_accessor :name
def initialize(name)
#name = name
end
end
class Things
def initialize(things = [])
#things = things
end
def push(thing)
#things.push(thing)
end
def append(other)
#things << other.to_a
end
def +(other)
Things.new(#things + other.to_a)
end
def to_a
#things
end
end
some_things = %w(Marty Fred Janice John).map { |name| Thing.new(name) }
things_1 = Things.new
some_things.first(2).each { |thing| things_1.push(thing) }
things_2 = Things.new
some_things.last(2).each { |thing| things_2.push(thing) }
things_1.append(things_2) # This actually appends to things_1 rather than creating a new object
new_things = things_1 + things_2 # Creates a new object
# => #<Things:0x007ff85a1aa770 #things=[
# #<Thing:0x007ff85a1aa928 #name="Marty">,
# #<Thing:0x007ff85a1aa900 #name="Fred">,
# #<Thing:0x007ff85a1aa8d8 #name="Janice">,
# #<Thing:0x007ff85a1aa8b0 #name="John">]>
Notes:
Modified the API a bit to simplify the code.
Added a new method + as its intuitive in this context.
Below is a fragement of my code
def LoadCategory(self, filter_string):
time.sleep(1)
self.heading = ""
self.Question_title = list()
self.Question_tag = list()
self.Question_body = list()
self.Question_who_ask = list()
self.Question_who_email = list()
self.Question_key = list()
self.Question_Date = list()
# list is then populated
def post(self):
self.response.write(self.Question_body)
# want to print out self.Question_body in post method.
But the list is empty. what is the right way to access the content of the variable ?
Quick solution assuming you are inside a request class. Although using self to assign variables to the class is not a good approach as said before.
def LoadCategory(self, filter_string):
time.sleep(1)
self.heading = ""
self.Question_title = list()
self.Question_tag = list()
self.Question_body = list()
self.Question_who_ask = list()
self.Question_who_email = list()
self.Question_key = list()
self.Question_Date = list()
# list is then populated
def post(self):
self.LoadCategory(filter_string)
self.response.write(self.Question_body)
Also it would be better if you name LoadCategory to load_category or loadcategory. Try following the PEP8 which states that the function names should be lowercase