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
Related
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&', '']
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
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.
This question already has answers here:
Python creating a dictionary of lists
(7 answers)
Closed 6 years ago.
I have thousands of products with ingredients of each for example:
ProductID | Ingredients
00001 | itemA, itemB, itemC, itemD
00002 | itemF, itemD, itemG, itemA, itemI
00003 | itemH, itemI, itemD, itemF, itemT,itemB, itemC
........ and so on.
I want to make a unique list of ingredients and make a map that what ingredients are in which product. So For example I want the resulting output in the following way:
{itemA: [00001,00011, 00005,00007]}
{itemB: [00003, 00002, 000056]}
{itemC: [00009, 00087, 00044, 00647, 00031, 00025]}
So the list size will be different for each item. Can somebody help me out in solving this problem? Thanks
Assuming its a text file, it could be something like this:
from collections import defaultdict
product_ingredients_mapping = defaultdict(list)
file_data = open('products.txt')
for row in file_data.readlines():
data = row.split('|')
ingredients = data[1].split(',')
product_id = data[0].strip()
for ingredient in ingredients:
product_ingredients_mapping[ingredient.strip()].append(product_id)
This question already has answers here:
How do I merge two dictionaries in a single expression in Python?
(43 answers)
Closed 7 years ago.
The question is
This is what I have so far:
dict(nafta_capitals) = canadian_capitals, mexican_capitals, us_capitals
Given three dictionaries, associated with the variables , canadian_capitals, mexican_capitals, and us_capitals, that map provinces or states to their respective capitals, create a new dictionary that combines these three dictionaries, and associate it with a variable , nafta_capitals.
You may need to use defaultdict-
Here nafta is used as key to the three ( canadian_capitals, mexican_capitals, us_capitals) as below-
>>>dic = defaultdict(list)
>>>lst = ['nafta1', 'canadian_capitals1', 'mexican_capitals1', 'us_capitals1', 'nafta2', 'canadian_capitals2', 'mexican_capitals2', 'us_capitals2']
>>>grouped_lst = [lst[i:i+4] for i in range(0,len(lst),4)]
>>>[['nafta1', 'canadian_capitals1', 'mexican_capitals1', 'us_capitals1'], ['nafta2', 'canadian_capitals2', 'mexican_capitals2', 'us_capitals2']]
>>>for i in grouped_lst:dic[i[0]]=i[1:]
>>>dic.items()
>>>[('nafta1', ['canadian_capitals1', 'mexican_capitals1', 'us_capitals1']), ('nafta2', ['canadian_capitals2', 'mexican_capitals2', 'us_capitals2'])]
>>>for i in dic.keys():print dic[i]
>>>['canadian_capitals1', 'mexican_capitals1', 'us_capitals1']
['canadian_capitals2', 'mexican_capitals2', 'us_capitals2']