I want to extract some keys and their values from a string.
It seems that the program needs using regex, but I do not know it well
It seems that the program needs using regex, but I do not know it well
The string is like this
adprod_type^B6^Apr_flag^B0^Asource^B^Asource_id^B^Aadprod_params^Bheight^D^Chtml^D<style>img{width:100% !important; height:100% !important}</style>\\n<script>gAdController.passback();</script>^Cwidth^D^Aadprodset_id^B9123^Aadserve^B
What expected is like this
adprod_type:'6',pr_flag:'0',source:'',source_id:'',adprod_params:{height:'',html:'<style>img{width:100% !important; height:100% !important}</style>\\n<script>gAdController.passback();</script>',width:''},adprodset_id:'9123',adserve:''
I tried this :
file_obj = open("/Users/icko/Documents/000/a.txt")
all_lines = file_obj.readlines()
for line in all_lines:
a = line.split('^A')
for i in a:
b = i.split('^B')
key = b[0]
val = b[1]
data[key] = val
if data['adprod_type'] == '6':
print('key=' + key)
print('value=' + val)
file_obj.close()
Thank you
I tried this:
if __name__ == '__main__':
file_obj = open("/Users/icko/Documents/000/a.txt")
all_lines = file_obj.readlines()
for line in all_lines:
data = {}
a = line.split('')
for i in a:
b = i.split('')
key = b[0]
val = b[1]
data[key] = val
if data['adprod_type'] == '6':
metadata = {}
metadata1 = {}
metadata2 = {}
metadata3 = {}
subdata = data['adprod_params']
c = subdata.split('')
data1 = c[0].split('')
data2 = c[1].split('')
data3 = c[2].split('')
key1 = data1[0]
key2 = data2[0]
key3 = data3[0]
val1 = data1[1]
val2 = data2[1]
val3 = data3[1]
metadata1[key1] = val1
metadata2[key2] = val2
metadata3[key3] = val3
metadata = dict(metadata1, **metadata2, **metadata3)
print(metadata)
success!
Related
I have a list named diags of type Linol_lwt.Diagnostic.t list
I want to update every element of this list and return another one.
Let's suppose that we have these modules:
module Diagnostic = struct
type t =
{ range : Range.t
; severity : DiagnosticSeverity.t Json.Nullable_option.t
[#default None] [#yojson_drop_default ( = )]
; code : Jsonrpc.Id.t Json.Nullable_option.t
[#default None] [#yojson_drop_default ( = )]
; source : string Json.Nullable_option.t
[#default None] [#yojson_drop_default ( = )]
; message : string
; tags : DiagnosticTag.t list Json.Nullable_option.t
[#default None] [#yojson_drop_default ( = )]
; relatedInformation :
DiagnosticRelatedInformation.t list Json.Nullable_option.t
[#default None] [#yojson_drop_default ( = )]
}
end
module Range = struct
type t =
{ start : Position.t
; end_ : Position.t
}
end
module Position = struct
type t =
{ line : int
; character : int
}
end
I want to update the field range, so I did this:
let diags2 = List.map ( fun (x: Linol_lwt.Diagnostic.t) ->
let ls = x.range.start in
let le = x.range.end_ in
{
Linol_lwt.Diagnostic.range =
{
start = { ls with line = ls.line + 1 };
end_ = { le with line = le.line + 1 }
}
}
) diags in
But it says that there is an error with this message:
Some record fields are undefined: severity code source message tags relatedInformation
As you mostly want to return the input value x with just the range field updated, you can use:
{ x with range = ... }
Or in place in your snippet above:
let diags2 = List.map ( fun (x: Linol_lwt.Diagnostic.t) ->
let ls = x.range.start in
let le = x.range.end_ in
{ x with
Linol_lwt.Diagnostic.range =
{
start = { ls with line = ls.line + 1 };
end_ = { le with line = le.line + 1 }
}
}
) diags in
To update multiple fields at once, use
{ x with range = ...; field2 = ... }
More detail here: https://dev.realworldocaml.org/records.html#scrollNav-4
I have method called 'encode(string_argument)' which converts string(sentence) to ascii and reverse it. I have to write method which decode the string.
Code:
str1 = 'This is sample text'
def encode(str1):
encoded_str = ''
for i in str1:
encoded_str += str(ord(i))
return encoded_str[::-1]
def decode(encoded_str):
rev_encoded_str = encoded_str[::-1]
# Incomplete
encoded_str = encode(str1)
decode(encoded_str)
Input for encode():
This is sample text
Output from encode():
6110211016112310180121190179511235115012351150140148
Input for decode():
6110211016112310180121190179511235115012351150140148
Output from decode():
This is sample text
Thanks in advance.
Finally got the solution:
def encode(str1):
encoded_str = ''
for i in str1:
encoded_str += str(ord(i))
return encoded_str[::-1]
def decode(encoded_str):
reverse_string = encoded_str[::-1]
temp_array = convert_to_possible_string_ascii(reverse_string)
final_decoded_string = ""
for x in temp_array:
# print(str(chr(int(x)))+": "+x)
final_decoded_string = final_decoded_string + str(chr(int(x)))
print(final_decoded_string)
return final_decoded_string
def convert_to_possible_string_ascii(str_array):
temp_array = []
temp_char = ""
counter = 0
for current_char in range(0, len(str_array), 1):
temp_char = temp_char+str_array[current_char]
counter = counter+1
if counter==1:
temp_var = is_valid_string_ascii(temp_char)
if temp_var:
temp_array.append(temp_char)
counter = 0
temp_char = ""
elif counter==2:
temp_var = is_valid_string_ascii(temp_char)
if temp_var:
temp_array.append(temp_char)
counter = 0
temp_char = ""
elif counter==3:
temp_var = is_valid_string_ascii(temp_char)
if temp_var:
temp_array.append(temp_char)
counter = 0
temp_char = ""
return temp_array
def is_valid_string_ascii(ascii_value):
valid_list = list(range(65, 91)) + list(range(97, 123)) +[32]
boolean_var = False
if int(ascii_value) in valid_list:
boolean_var = True
return boolean_var
str1 = 'This is sample text'
encoded_str = encode(str1)
decode(encoded_str)
I am having trouble storing the ID to keys, like a sub (parent-child) kind of thing. I spent hours on it and could not figure a way to accomplish this. What output I am expecting is at the end of this post. Any help would be great.
import sys
import collections
dict = collections.OrderedDict()
dict["A.1"] = {"parent_child":0}
dict["A.1.1"] = {"parent_child":1}
dict["A.1.1.1"] = {"parent_child":2}
dict["A.1.1.2"] = {"parent_child":2}
dict["A.1.1.3"] = {"parent_child":2}
dict["A.1.2"] = {"parent_child":1}
dict["A.1.2.1"] = {"parent_child":2}
dict["A.1.2.2"] = {"parent_child":2}
dict["A.1.2.2.1"] = {"parent_child":3}
dict["A.1.2.2.2"] = {"parent_child":3}
dict["A.1.2.3"] = {"parent_child":2}
dict["A.1.3"] = {"parent_child":1}
dict["A.1.4"] = {"parent_child":1}
print(dict)
new_dict = {}
p = 0 # previous index
i = 0 # current
n = 1 # next index
current_PC = 0 # current parent_child
next_PC = 0 # next parent_child
previous_id = ""
current_id = ""
next_id = ""
change_current = True
change = True
lst = []
while(True):
if change_current:
current_id = dict.keys()[i]
current_PC = dict.values()[i]["parent_child"]
change_current = False
try:
next_id = dict.keys()[n]
next_PC = dict.values()[n]["parent_child"]
except:
pass # it will go out of index
print("KEY {0}".format(current_id))
if next_PC > current_PC:
if next_PC - current_PC == 1:
lst.append(next_PC)
next_PC += 1
print("next_PC: {0}".format(next_PC))
if next_PC == current_PC:
new_dict[current_id] = lst
lst = []
break
print(new_dict)
Trying to make output looks like this (at in similar way), the new_dict should look like:
new_dict["A.1"] = ["A.1.1", "A.1.2", "A.1.3", "A.1.4"]
new_dict["A.1.1"] = ["A.1.1.1", "A.1.1.2", "A.1.1.3"]
new_dict["A.1.1.1"] = []
new_dict["A.1.1.2"] = []
new_dict["A.1.1.3"] = []
new_dict["A.1.2"] = ["A.1.2.1", "A.1.2.2", "A.1.2.3"]
new_dict["A.1.2.1"] = []
new_dict["A.1.2.2"] = ["A.1.2.2.1", "A.1.2.2.2"]
new_dict["A.1.2.2.1"] = []
new_dict["A.1.2.2.2"] = []
new_dict["A.1.2.3"] = []
new_dict["A.1.3"] = []
new_dict["A.1.4"] = []
This gives you the output you are asking for. Since i did not see a {"parent_child":...} in you desired output i did not proceed with anything else.
options = ["A.1","A.1.1","A.1.1.1","A.1.1.2","A.1.1.3","A.1.2","A.1.2.1","A.1.2.2","A.1.2.2.1","A.1.2.2.2","A.1.2.3","A.1.3","A.1.4"]
new_dict = {}
for i, key in enumerate(options):
new_dict[key] = []
ls = []
for j, opt in enumerate(options):
if (key in opt) and (len(opt)-len(key)==2):
new_dict[key].append(opt)
print(new_dict)
EDIT
Using the comment of #Ranbir Aulakh
options = ["A.1","A.1.1","A.1.1.1","A.1.1.2","A.1.1.3","A.1.2","A.1.2.1","A.1.2.2","A.1.2.2.1","A.1.2.2.2","A.1.2.3","A.1.3","A.1.4"]
new_dict = {}
for i, key in enumerate(options):
new_dict[key] = []
ls = []
for j, opt in enumerate(options):
if (key in opt) and (len(opt.split("."))-len(key.split("."))==1):#(len(opt)-len(key)==2):
new_dict[key].append(opt)
print(new_dict)
I am getting the error need more than 1 value to unpack i am using defaultDict to make my list to dictionary.
def getTabsCols(request):
proj_name = request.GET.get('projname')
cursor = connection.cursor()
proj_details = TProjects.objects.get(
attr_project_name=proj_name, attr_project_type='Structure', attr_is_active=1)
pid = proj_details.project_id
query = 'call SP_Get_TABCOL_NAMES('+str(pid)+')'
cursor.execute(query)
proj_details = TProjects.objects.get(
attr_project_name=proj_name, attr_project_type='Structure', attr_is_active=1)
pid = proj_details.project_id
query = 'call SP_Get_TABCOL_NAMES('+str(pid)+')'
cursor.execute(query)
result = cursor.fetchall()
tab_list = []
tab_col_list = []
prd = {}
res = []
for row in result:
tabs = collections.OrderedDict()
schema_name = row[1]
table_name = row[3]
tab = (schema_name + '.' + table_name).encode('utf8')
tabs[tab] = row[5].encode('utf8')
tab_list.append(tabs)
d = collections.defaultdict(set)
for k, v in tab_list:
d1[k].append(v)
d = dict((k, tuple(v)) for k, v in d1.iteritems())
return HttpResponse(d, content_type="text/html")
I am using below code snippet to get the red reduced price from amazon but simehow I am always getting the old price and not the reduced red one.
enter code here`def getSignedUrlAmazon(searchvalue):
params = {'ResponseGroup':'Medium',
'AssociateTag':'',
'Operation':'ItemSearch',
'SearchIndex':'All',
'Keywords':searchvalue}
action = 'GET'`enter code here`
server = "webservices.amazon.in"
path = "/onca/xml"
params['Version'] = '2011-08-01'
params['AWSAccessKeyId'] = AWS_ACCESS_KEY_ID
params['Service'] = 'AWSECommerceService'
params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# Now sort by keys and make the param string
key_values = [(urllib.quote(k), urllib.quote(v)) for k,v in params.items()]
key_values.sort()
# Combine key value pairs into a string.
paramstring = '&'.join(['%s=%s' % (k, v) for k, v in key_values])
urlstring = "http://" + server + path + "?" + \
('&'.join(['%s=%s' % (k, v) for k, v in key_values]))
# Add the method and path (always the same, how RESTy!) and get it ready to sign
hmac.update(action + "\n" + server + "\n" + path + "\n" + paramstring)
# Sign it up and make the url string
urlstring = urlstring + "&Signature="+\
urllib.quote(base64.encodestring(hmac.digest()).strip())
return urlstring
forgot the price grabbing part:
def getDataAmazon(searchvalue,PRICE, lock):
try:
searchvalue = removeStopWord(searchvalue)
url = getSignedUrlAmazon(searchvalue)
data = etree.parse(url)
root = objectify.fromstring(etree.tostring(data, pretty_print=True))
gd=[]
gd1=[]
counter = 0
if hasattr(root, 'Items') and hasattr(root.Items, 'Item'):
for item in root.Items.Item:
cd={}
priceCheckFlag = False
try :
if hasattr(item.ItemAttributes, 'EAN'):
cd['EAN'] = str(item.ItemAttributes.EAN)
elif hasattr(item, 'ASIN'):
cd['ASIN'] = str(item.ASIN)
cd['productName'] = str(item.ItemAttributes.Title)
if hasattr(item, 'SmallImage'):
cd['imgLink'] = str(item.SmallImage.URL)
elif hasattr(item, 'MediumImage'):
cd['imgLink'] = str(item.MediumImage.URL)
cd['numstar'] = "0"
cd['productdiv'] = '1'
cd['sellername'] = 'Amazon'
if hasattr(item, 'DetailPageURL'):
cd['visitstore'] = str(item.DetailPageURL)
if hasattr(item.ItemAttributes, 'ListPrice') and hasattr(item.ItemAttributes.ListPrice, 'Amount'):
cd['price'] = item.ItemAttributes.ListPrice.Amount/100.0
elif hasattr(item, 'OfferSummary') and hasattr(item.OfferSummary, 'LowestNewPrice'):
cd['price'] = item.OfferSummary.LowestNewPrice.Amount/100.0