How to write regular expression Python [duplicate] - python

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 3 years ago.
I'd like to return the value of left battery capacity parsed from the given string. It means I want to get CurrentCapacity / MaxCapacity.
data = '''
"SuperMaxCapacity" =0
"MaxCapacity": +4540;
'CurrentCapacity'= 2897,
"LegacyBatteryInfo" = {"Amperage"=18446744073709550521,"Flags"=4,"Capacity"=4540,"Current"=2897,"Voltage"=7283,"Cycle Count"=406}
"MegaMaxCapacity" = 6700
'''

This will do the job quite nicely, and will get the match, even though your data input format is quite iffy:
import re
data = '''
"SuperMaxCapacity" =0
"MaxCapacity": +4540;
'CurrentCapacity'= 2897,
"LegacyBatteryInfo" = {"Amperage"=18446744073709550521,"Flags"=4,"Capacity"=4540,"Current"=2897,"Voltage"=7283,"Cycle Count"=406}
"MegaMaxCapacity" = 6700
'''
max_capacity = re.search(r"[\"']MaxCapacity.*?[:=].*?(\d+)", data).group(1)
current_capacity = re.search(r"[\"']CurrentCapacity.*?[:=].*?(\d+)", data).group(1)
print("Max capacity:", max_capacity)
print("Current capacity:", current_capacity)
Output:
Max capacity: 4540
Current capacity: 2897

Related

Updating a set with another returns NONE [duplicate]

This question already has answers here:
Why doesn't a python dict.update() return the object?
(11 answers)
python setdefault(key,set())).update(... returns None
(1 answer)
Why does dict(k=4, z=2).update(dict(l=1)) return None in Python? [duplicate]
(3 answers)
Closed last year.
Trying to sum to sets from 2 different txt files with very similar content.
examplet of content:
https://articulo.mercadolibre.com.ar/MLA-1113638999-placa-de-video-colorful-gt710-nf-1gb-ddr3-garantia-oficial-_JM;Placa De Video Colorful Gt710 Nf 1gb Ddr3 Garantia Oficial;gold_special;True;6999
https://articulo.mercadolibre.com.ar/MLA-795327882-placa-de-video-geforce-gt-710-1gb-ddr3-pc-gamer-gt710-dx12-_JM;Placa De Video Geforce Gt 710 1gb Ddr3 Pc Gamer Gt710 Dx12;gold_special;True;7499
I'm trying to do that with the following code (simplifaction of the original):
with open("gt-710.txt","r") as f:
a = f.readlines()
with open("gt-7102.txt","r") as f:
b = f.readlines()
c = set(a).update(set(b))
print(c)
The output i'm getting constantly is NONE, I tried printing each set without updating and they do so properly, but once I try to sume them up they return NONE.
update method of set returns None. So what you can do is use a instead of the output of that line;
a = set(a)
a.update(set(b))
Or better yet I would do
c = set(a) | set(b)

Python extract parameters from url [duplicate]

This question already has answers here:
Retrieving parameters from a URL
(20 answers)
Closed 1 year ago.
I need your help on this, I have a url something like this
url = "https://tracking.example.com:443/attribution_tracking/conversions/1980.js?p=https://example.com/search?addsearch=test+search&e="
Need some python code to extract the url parameters and the result would be an array something like this
extracted_parameters = ["p=", "addsearch=", "e="]
This uses splitting.
url = "https://tracking.example.com:443/attribution_tracking/conversions/1980.js?p=https://example.com/search?addsearch=test+search&e="
def extract(url):
ret = []
p = url.split('p=')[1].split('addsearch')[0]
addsearch = url.split('addsearch=')[1].split('e=')[0]
e = url.split('e=')[1]
ret.append(p)
ret.append(addsearch)
ret.append(e)
return ret
# start
res = extract(url)
print(res)
Output
['https://example.com/search?', 'test+search&', '']

How do I use an input to call a function? [duplicate]

This question already has answers here:
How to access (get or set) object attribute given string corresponding to name of that attribute
(3 answers)
Closed 2 years ago.
how can I make a print to change to the input value?
import cryptowatch as cw
time = input("Time:") #15m, 1h , 1d
x = cw.markets.get("KRAKEN:ATOMEUR", ohlc = True, periods = [time])
print(x.of_15m[1][4]))
for example:
time = input("Time:") #1h
print(x.of_1h[1][4])
or:
time = input("Time:") #1d
print(x.of_1d[1][4])
EDIT:
I leave more information
cryptowatch-sdk
https://github.com/cryptowatch/cw-sdk-python
Module file where the functions are:(line 255)
https://github.com/cryptowatch/cw-sdk-python/blob/master/cryptowatch/resources/markets.py
I couldn't really test this properly since I don't have cryptowatch installed, but I think it would work. It uses the user's input to determine the name of an x object attribute, and then uses getattr() to retrieve its current value.
import cryptowatch as cw
time = input("Time:")
x = cw.markets.get("KRAKEN:ATOMEUR", ohlc=True, periods=[time])
interval = getattr(x, 'of_'+time, None)
if interval is not None:
print(interval[1][4])
else:
print('Error: unknown time', time)

Wrong sequence for list using sorted() [duplicate]

This question already has answers here:
Sort a python list of strings with a numeric number
(3 answers)
Closed 3 years ago.
I have some images which I generate from url with random pictures. Then I try to sort them to work with it properly, but they sorting is messed up. Appreciate any advices or pointing to what I missing
Code ( image list generating ):
def image_downloader():
image_url = 'url'
for count in tqdm(range(20)):
image_data = requests.get(image_url).content
with open(f'image_{count}.jpg', 'wb') as handler:
handler.write(image_data)
sleep(0.5)
And my sorting ( trying to get it by generated picture "id" ):
local_folder_content = os.listdir('.')
images_list = list((image for image in local_folder_content if image.endswith('.jpg')))
pprint((sorted(images_list, key=lambda x: x[:-4].split('_')[1])))
Result( sorting is messed up) :
['image_0.jpg',
'image_1.jpg',
'image_10.jpg',
'image_11.jpg',
'image_12.jpg',
'image_13.jpg',
'image_14.jpg',
'image_15.jpg',
'image_16.jpg',
'image_17.jpg',
'image_18.jpg',
'image_19.jpg',
'image_2.jpg',
'image_3.jpg',
'image_4.jpg',
'image_5.jpg',
'image_6.jpg',
'image_7.jpg',
'image_8.jpg',
'image_9.jpg']
You can try something like this :
images_list.sort(key= lambda i: int(i.lstrip('image_').rstrip('.jpg')))
You have to generate all filenames with two (or more) digits:
with open(f'image_{str(count).zfill(2)}.jpg', 'wb') as handler:
Output:
image_01.jpg
image_02.jpg
image_04.jpg
In this case your images will be correctly sorted.

List on python: where has the `u` come from? [duplicate]

This question already has answers here:
What exactly do "u" and "r" string prefixes do, and what are raw string literals?
(7 answers)
Closed 8 years ago.
Quick question:
disc_list=[] #creating an empty list to put the discs into
rad = 70
for i in range(5):
disc_list.append(cmds.polyCylinder( name = 'disc' + str(i), radius = rad, height = 10)[0]) # create discs
cmds.move(0, 10*i, 0, ('disc' + str(i)))
rad = rad*0.7
print disc_list
anyone know why when I print the disc_list, this is returned:
[u'disc0', u'disc1', u'disc2', u'disc3', u'disc4']
where has the u come from?
The u simply denotes that it is a unicode string. You should not worry about it. When you print it, it will still be the same.
for i in disc_list:
print i
[OUTPUT]
disc0
disc1
disc2
disc3
disc4
Suggested link

Categories