我正在解析一个URL,提取标记和值。我创建了所有标签的列表,并尝试将值附加到适当的列表中。下面有一个示例URL,其中包含三个“ utm”标记,utm_source,utm_medium和utm_campaign。元组(x,y)具有标签名称和值。
我的问题在最后一行。我想将值(y)“附加”到与标签(x)同名的LIST上,这可能吗?我应该在字典中创建字典吗? TIA。以利
================================================ ==========================
utm_source = []
utm_medium = []
utm_campaign = []
url = 'https://www.focus.de/politik/ausland/weltkriegs-entschaedigungen-ziehen-in-die-schlacht-polen-und-griechen-kaempfen-nun-gemeinsam-um-reparationen_id_11122350.html?utm_source=facebook&utm_medium=social&utm_campaign=facebook-focus-online&fbc=facebook-focus-online&ts=201909091311&cid=09092019&fbclid=IwAR3R6tPi3TvS11j5ZzC_UCRMxgaY2Op6UDBKa5jKPIm4ZAhaErLMMY4WaqE'
terms = re.findall("(utm_.+?)\&", url)
print(terms)
for t in range(len(terms)):
try:
x,y = terms[t].split('=')
except:
x = 'excep'
x.append(y)
要成对正确存储它们,是的,字典是个好方法,您也可以直接遍历这些术语
d = {}
for term in terms:
try:
x, y = term.split('=')
except:
x, y = 'excep', None
d[x] = y
使用字典理解方式
d = {k: v for k, v in [term.split('=') for term in terms]}