【问题标题】:Parsing list of URLs with regex patterns使用正则表达式模式解析 URL 列表
【发布时间】:2019-01-23 03:02:55
【问题描述】:

我有一个大的 URL 文本文件(>100 万个 URL)。 URL 代表跨多个不同域的产品页面。

我正在尝试从每个 URL 中解析出 SKU 和产品名称,例如:

  • www.amazon.com/totes-Mens-Mike-Duck-Boot/dp/B01HQR3ODE/
    • 手提包-男装-Mike-Duck-Boot
    • B01HQR3ODE
  • www.bestbuy.com/site/apple-airpods-white/5577872.p?skuId=5577872
    • apple-airpods-白色
    • 5577872

我已经找到了单独的正则表达式模式,用于解析我列表中所有域的 URL 的两个组成部分(产品名称和 SKU)。这是近 100 种不同的模式。

虽然我已经弄清楚如何一次测试这个 URL/模式,但我无法弄清楚如何构建一个脚本,该脚本将读取我的整个列表,然后根据相关的正则表达式模式。有什么建议可以最好地解决这个问题吗?

如果我的输入是一列 (URL),我想要的输出是 4 列(URL、域、产品名称、SKU)。

【问题讨论】:

  • 显示您当前的代码/正则表达式/等
  • 为澄清起见,我并没有要求有人为我编写代码,而是在寻找如何最好地解决这个问题的指导。我目前拥有的只是我使用各种正则表达式模式与 re 库中的 match 和 sub 函数测试出来的查询的混搭。

标签: python regex python-3.x


【解决方案1】:

由于从 URL 中提取域名相当容易,您可以将域名映射到该域的模式。

像这样:

dict = {
'domain1.com': 'regex_pattern_for_domain1', 
'domain2.com': 'regex_pattern_for_domain2'
}

现在您应该逐行阅读您的文件并应用通用正则表达式来提取您将用于获取特定正则表达式的域名。

def extract_data(url, regex_pattern):
    # code to extract product name and SKU
    return ['product_id', 'sku'] 

def extract_domain(url):
    # apply general regex pattern to extract URL
    return 'domain name'

parsed_data = []
with open('urls.txt') as f:
    url = f.readline()
    domain = extract_domain(url) # call function that extracts domain from the URL
    domain_regex = dict[domain] # use dictionary to get the regex for the given domain
    data = extract_data(url, domain_regex) # call function to extract data from the given URL and regex for that domain
    data.append(domain)
    data.append(url)
    parsed_data.append(data) # append extracted data to the list, or save it to another file if it is too big to fit into memory.

【讨论】:

    【解决方案2】:

    虽然可以将这一切整合到一个庞大的正则表达式中,但这可能不是最简单的方法。相反,我会使用两遍策略。为适用于该域的正则表达式模式制作一个域名字典。在第一遍中,使用适用于所有 URL 的单个正则表达式检测该行的域。然后使用发现的域在您的 dict 中查找适当的正则表达式以提取该域的字段。

    【讨论】:

      猜你喜欢
      • 2012-08-23
      • 2011-03-20
      • 1970-01-01
      • 2012-11-30
      • 2012-06-15
      • 1970-01-01
      相关资源
      最近更新 更多