matching string using regular expression - regex

text = "hellovision hey creator yoyo b creator great publisher"
I want to extract creator's name and publisher's name from text.
The result will be,
creator = hellovision hey, yoyo
publisher = great
How can I get text using regular expression?
Do I need to use span()..?
This is my code.
def preprocess2(text):
text_list = test.split(' ')
lyricist = []
composer = []
music_arranger = []
temp = []
lyricist.clear()
composer.clear()
music_arranger.clear()
for i in range(0, len(text_list)):
if text_list[i] == 'creator':
print(len(text_list))
for a in range(0, i-1):
temp.append(text_list[a])
lyricist.append(''.join(temp))
temp.clear()
for b in range(0, i+1):
print(b)
text_list.pop(b)
print(len(text_list))
break
elif text_list[i] == 'pulisher':
for a in range(0, i-1):
temp.append(text_list[a])
composer.append(''.join(temp))
temp.clear()
for b in range(0, i+1):
text_list.pop(b)
break
i = i +1
return text_list

If you split your array using regex with a capture group, the value that you split on will also be passed into the output array.
You can then loop through looking for 'creator' or 'publisher' and in each case, pass the previous entry into the proper collection.
const text = "hellovision hey creator yoyo b creator great publisher"
const splitArr = text.split(/(creator|publisher)/)
const creators = [], publishers = []
let i = -1, len = splitArr.length
while(++i < len){
if(splitArr[i] == "creator") creators.push(splitArr[i-1].trim())
else if(splitArr[i] == "publisher") publishers.push(splitArr[i-1].trim())
}
console.log("creators: ", creators)
console.log("publishers: ", publishers)

Related

intField does not display changes

I am writing a script to simplify a tedious task when using Vray, but I am stuck with the intFields that are supposed to allow the user to type in a int value that triggers an certain action when hitting the button. I simplified the code to only the necessary parts. No matter what I change the value to, it is always 0 in the Script Editor output.
import maya.cmds as cmds
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (300,500))
cmds.columnLayout(adj = True)
cmds.text (l = 'type in MultimatteID to select matching shaders \n or specify ObjectID to select matching objects \n __________________________________________ \n')
cmds.text (l = 'MultimatteID: \n')
cmds.intField( "MultimatteID", editable = True)
MultimatteIdButton = cmds.button(l = 'Go!', w = 30, h = 50, c = 'multimatteChecker()')
cmds.text (l = '\n')
cmds.showWindow(idManagerUI)
MultimatteIdInput = cmds.intField( "MultimatteID", q = True, v = True)
def multimatteChecker():
print MultimatteIdInput
Three things:
First, as written you can't be sure that the intField MultimatteID is actually getting the name you think it should have. Maya widget names are unique, like maya object names -- you may name it MultimatteID but actually get back a widget named MultimatteID2 because you have an undeleted window somewhere (visible or not) with a similarly named control.
Second, the code you pasted queries the value of the control immediately after the window is created. It should always print out the value you gave it on creation.
Finally -- don't use the string version of command assignment in your button. It's unreliable when you move from code in the listener to working scripts.
This should do what you want:
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (300,500))
cmds.columnLayout(adj = True)
cmds.text (l = 'type in MultimatteID to select matching shaders \n or specify ObjectID to select matching objects \n __________________________________________ \n')
cmds.text (l = 'MultimatteID: \n')
# store the intField name
intfield = cmds.intField( "MultimatteID", editable = True)
cmds.text (l = '\n')
# define the function before assigning it.
# at this point in the code it knows what 'intfield' is....
def multimatteChecker(_):
print cmds.intField( intfield, q = True, v = True)
#assign using the function object directly
MultimatteIdButton = cmds.button(l = 'Go!', w = 30, h = 50, c = multimatteChecker)

Getting "wrong number of bind variables" when I'm trying to write a Rails finder method

I’m using Rails 4.2.3. I’m having trouble passing a variable number of search criteria to my Rails finder method. I have
user = current_user
search_criteria = ["my_objects.user_id = ?"]
search_values = [user.id]
start_date = params[:start_date]
if start_date.present?
start_date_obj = Date.strptime(start_date, "%m/%d/%Y")
search_criteria.push("my_objects.start_date >= ?")
search_values.push(start_date_obj)
else
start_date = my_object.find_user_first_my_object_date(user)
#default_start_date = start_date.to_time.strftime("%m/%d/%Y") if start_date.present?
end
end_date = params[:end_date]
if end_date.present?
end_date_obj = Date.strptime(end_date, "%m/%d/%Y")
search_criteria.push("my_objects.end_date <= ?")
search_values.push(end_date_obj)
else
end_date = my_object.find_user_last_my_object_date(user)
#default_end_date = end_date.to_time.strftime("%m/%d/%Y") if end_date.present?
end
distance = params[:distance]
if distance.present?
distance_parts = distance.split(" ")
search_criteria.push("my_objects.distance = ?")
search_criteria.push("my_objects.distance_unit_id = ?")
search_values.push("#{distance_parts[0]}")
search_values.push("#{distance_parts[1]}")
end
#user_my_objects = MyObjectTime.joins(:my_object).where(search_criteria.join(" AND "), search_values)
.order("my_objects.day")
But this results in the error
wrong number of bind variables (1 for 5) in: my_objects.user_id = ? AND my_objects.start_date >= ? AND my_objects.end_date <= ? AND my_objects.distance = ? AND my_objects.distance_unit_id = ?
I think Rails is treating my “search_values” array as a single value but I want it to pass each value of the array as an argument into the search condition. How do I fix the above?
If I've read the question right, this boils down to
values = ['a', 'b', 'c']
SomeModel.where("foo = ? AND bar = ? AND baz = ?", values)
Throwing an error about an incorrect number of bind variables. To unpack an array and use its values as individual arguments you use the splat operator:
SomeModel.where("foo = ? AND bar = ? AND baz = ?", *values)

Creating a if/else that appends data from mult. scraped pages if counts differ?

I"m trying to scrape Oregon teacher licensure information that looks like this or this(this is publicly available data)
This is my code:
for t in range(0,2): #Refers to txt file with ids
address = 'http://www.tspc.oregon.gov/lookup_application/LDisplay_Individual.asp?id=' + lines2[t]
page = requests.get(address)
tree = html.fromstring(page.text)
count = 0
for license_row in tree.xpath(".//tr[td[1] = 'License Type']/following-sibling::tr[1]"):
license_data = license_row.xpath(".//td/text()")
count = count + 1
if count==1:
ltest1.append(license_data)
if count==2:
ltest2.append(license_data)
if count==3:
ltest3.append(license_data)
with open('teacher_lic.csv', 'wb') as pensionfile:
writer = csv.writer(pensionfile, delimiter="," )
writer.writerow(["Name", "Lic1", "Lic2", "Lic3"])
pen = zip(lname, ltest1, ltest2, ltest3)
for penlist in pen:
writer.writerow(list(penlist))
The problem occurs when this happens: teacher A has 13 licenses and Teacher B has 2. In A my total count = 13 and B = 2. When I get to Teacher B and count equal to 3, I want to say, "if count==3 then ltest3.append(licensure_data) else if count==3 and license_data=='' then license3.append('')" but since there's no count==3 in B there's no way to tell it to append an empty set.
I'd want the output to look like this:
Is there a way to do this? I might be approaching this completely wrong so if someone can point me in another direction, that would be helpful as well.
There's probably a more elegant way to do this but this managed to work pretty well.
I created some blank spaces to fill in when Teacher A has 13 licenses and Teacher B has 2. There were some errors that resulted when the license_row.xpath got to the count==3 in Teacher B. I exploited these errors to create the ltest3.append('').
for t in range(0, 2): #Each txt file contains differing amounts
address = 'http://www.tspc.oregon.gov/lookup_application/LDisplay_Individual.asp?id=' + lines2[t]
page = requests.get(address)
tree = html.fromstring(page.text)
count = 0
test = tree.xpath(".//tr[td[1] = 'License Type']/following-sibling::tr[1]")
difference = 15 - len(test)
for i in range(0, difference):
test.append('')
for license_row in test:
count = count + 1
try:
license_data = license_row.xpath(".//td/text()")
except NameError:
license_data = ''
if license_data=='' and count==1:
ltest1.append('')
if license_data=='' and count==2:
ltest2.append('')
if license_data=='' and count==3:
ltest3.append('')
except AttributeError:
license_data = ''
if count==1 and True:
print "True"
if count==1:
ltest1.append(license_data)
if count==2 and True:
print "True"
if count==2:
ltest2.append(license_data)
if count==3 and True:
print "True"
if count==3:
ltest3.append(license_data)
del license_data
for endorse_row in tree.xpath(".//tr[td = 'Endorsements']/following-sibling::tr"):
endorse_data = endorse_row.xpath(".//td/text()")
lendorse1.append(endorse_data)

Changing values in an list? [duplicate]

I want to remove some words from a list of words. I have a list with a recurring word and I want to get rid of it and I have no idea. I don't know whether I need to use a whole loop or regex.
from xlrd import open_workbook,error_text_from_code
book = open_workbook(inp)
sheet0 = book.sheet_by_index(0)
x = 0
y = 0
countr = sheet0.nrows
countc = sheet0.ncols
names = ''
variables = []
"different variables-----------------"
while x < countr -1:
x = x+1
y = y+1
cell = sheet0.cell(y,0)
names = names+ str(cell)
cell = sheet0.cell(y,1)
variables.append(cell)
country_text = names
countries = ', '.join(re.findall("('.*?')", country_text))
countries = countries.split()
print (variables)
print (countries)
What I get :
[number:150000.0, number:140000.0, number:300000.0]
and I need
[150000, 140000, 300000]
If you use a loop you can access to the value of a cell using this function:
sheet0.cell_value(curr_row, curr_cell)

Django Filter Loop OR

Does anyone know how I get Django Filter build an OR statement? I'm not sure if I have to use the Q object or not, I thought I need some type of OR pipe but this doesn't seem right:
filter_mfr_method = request.GET.getlist('filter_mfr_method')
for m in filter_mfr_method:
designs = designs.filter(Q(mfr_method = m) | m if m else '')
# Or should I do it this way?
#designs = designs.filter(mfr_method = m | m if m else '')
I would like this to be:
SELECT * FROM table WHERE mfr_method = 1 OR mfr_method = 2 OR mfr_method = 3
EDIT: Here is what Worked
filter_mfr_method = request.GET.getlist('filter_mfr_method')
list = []
for m in filter_mfr_method:
list.append(Q(mfr_method = m))
designs = designs.filter(reduce(operator.or_, list))
What about:
import operator
filter_mfr_method = request.GET.getlist('filter_mfr_method')
filter_params = reduce(operator.or_, filter_mfr_method, Q())
designs = designs.filter(filter_params)
Something I used before:
qry = None
for val in request.GET.getlist('filter_mfr_method'):
v = {'mfr_method': val}
q = Q(**v)
if qry:
qry = qry | q
else:
qry = q
designs = designs.filter(qry)
That is taken from one of my query builders.