【发布时间】:2021-06-22 10:58:01
【问题描述】:
我正在从 Microsoft 获取有关他们计划的数据,这是数据参考网页
我正在处理表格数据,以最初为第一列获取带有 guid 的相应产品,这很容易,但最后,他们只是在其中使用了中断标签。这是我的代码。
import requests
from requests.api import head
from bs4 import BeautifulSoup
import pandas as pd
import json
import re
url = "https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/licensing-service-plan-reference#feedback"
payload = {}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
soup = BeautifulSoup(response.content, 'lxml')
table = soup.find( "table" )
df = pd.read_html(str(table))[0]
df = df.drop(labels=['Service plans included'],
axis='columns')
json_dict = json.loads(df.to_json(orient='records'))
regex = r"([A-Z ]+ \(.*?\))"
microsoft_processed_data = []
for item in json_dict:
plan_data = item["Service plans included (friendly names)"]
matches = re.findall(regex, plan_data)
dict = {}
for match in matches:
dict_key = match.split("(", )[1]
dict_key = dict_key.replace(")", "")
dict_value = match.split(" (")[0]
print(dict_key + " : " + dict_value)
dict[dict_key] = dict_value
item["Service plans included (friendly names)"] = dict
microsoft_processed_data.append(item)
with open('data.json', 'w') as f:
json.dump(microsoft_processed_data, f, indent = 4)
直到他们开始在他们的计划名称中使用括号并且我的正则表达式失败,它在一个组中工作。
如果我们考虑这个样本行
在线交换(计划 1)(9aaf7827-d63c-4b61-89c3-182f06f82e5c)
然后根据我的正则表达式,它从右括号的开头到结尾拾取文本。
所以,我的正则表达式是我收集的数据,直到 > 在线交换(计划 1)
但我希望获取数据直到它的 guid id,然后分隔字典的名称。
这是我的预期字典示例
{
"EXCHANGE ONLINE (PLAN 1)" : "9aaf7827-d63c-4b61-89c3-182f06f82e5c"
}
【问题讨论】:
标签: python regex regex-group