Python extract parameters from url [duplicate] - python

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&', '']

Related

Add words in a link [duplicate]

This question already has answers here:
Add params to given URL in Python
(15 answers)
Closed 2 years ago.
I am creating a searching system in a personal website. I have a database with a list of products, and for each product i would like to search it on the website by the requests module.
The main link is: "https://website.com/search/album?uid=1&q="
Example:
I am looking for Iphone 12 256 GB.
The link should be: https://website.com/search/album?uid=1&q=Iphone+12+256+GB.
I've started just defing the main variable:
main_link = "https://website.com/search/album?uid=1&q="
product_name = "Iphone 12 256 GB"
product_name_to_search = product_name.split()
for product_word in product_name_to_search:
main_link + str(product_word)
Frankly, i dont know how to go on.
product_name = product_name.replace(" ","+")
main_link = f"https://website.com/search/album?uid=1&q={product_name}"
Try this:
main_link += '+'.join(product_name.split())
>>> print(main_link)
https://website.com/search/album?uid=1&q=Iphone+12+256+GB

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)

How to write regular expression Python [duplicate]

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

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.

what I should change in this code to return two lists? [duplicate]

This question already has answers here:
Alternatives for returning multiple values from a Python function [closed]
(14 answers)
Closed 8 years ago.
def ethos(file):
f = open(file)
raw = f.read()
token = nltk.word_tokenize(raw)
words_to_match = ['love' , 'good' , 'excellent' , 'perfect' , 'brilliant']
words_to_match2 = ['bad' , 'primitive' , 'struggle' , 'annoying' , 'problem' , 'time-consuming', 'fiddly']
positive_tokens = []
negative_tokens = []
for tokens in token:
if tokens in words_to_match:
positive_tokens.append(tokens)
and tokens in words_to_match2:
negative_tokens.append(tokens)
return negative_tokens
I wrote this code with an intention of returning two lists one positive and one negative, I cannot give two return statement, but I want two separate lists. And this program is showing syntax error in the 'and' statement, kindly help.
Change the last part of your program in the following way:
for tokens in token:
if tokens in words_to_match:
positive_tokens.append(tokens)
if tokens in words_to_match2:
negative_tokens.append(tokens)
return (positive_tokens, negative_tokens)
this will return a tuple with two elements. You use it as such:
(positive_tokens, negative_tokens) = ethos(yourfile)
I would do something like:
def ethos(file):
...
positive_tokens = [t for t in token if t in words_to_match]
negative_tokens = [t for t in token if t in words_to_match2]
return positive_tokens, negative_tokens
You can use this like:
positive, negative = ethos("somefile.txt")
See How do you return multiple values in Python? for a more advanced discussion on returning multiple values from functions

Categories