如何修复忽略if语句的正则表达式功能?

时间:2019-03-23 13:58:35

标签: python regex parsing text

我有以下python数据框

enter image description here

我已经编写了以下代码:

网址

  1. 对于Landing_Page列中的每个URL,搜索其中包含“ / 2019 /”的URL,并为其指定一个新变量“ new_model_core_incentives”
  2. 对于Landing_Page列中的每个URL,搜索包含2019年以外的任何年份的URL,然后为它们分配一个名为“ used_model_core_incentives”的新变量

关键字

  1. 搜索关键字列的每一行,并为其中包含“ 2019”的关键字创建一个新变量并将其命名为new_word
  2. 搜索关键字列的每一行,对于没有年份的关键字,将其称为new_word
  3. 搜索关键字列的每一行,对于包含年份不是2019的关键字,将它们称为old_words
for Landing_Page in zip(df.Landing_Page):
      # the url
    if "/2019/" in Landing_Page:
        new_model_core_incentives = Landing_Page
        print(f"new_model_core_incentives {new_model_core_incentives}")
    elif re.search("/(?:(?:20)|(?:19))\d{2}/", url):
        used_model_core_incentives = Landing_Page 
        print(f"used_model_core_incentives {used_model_core_incentives}")    

        # the "keywords"
    if "2019" in Keyword:
        new_word = Keyword
        print(f"new_word {new_word}")
    elif re.search("(?:(?:20)|(?:19))\d{2}", Keyword) is None:
        old_word = Keyword
        print(f"old_word {old_word}")

运行此代码时,出现以下错误:

1. List item

当我尝试分别运行这些块时,我遇到了一个问题,尽管所有URL中都包含“ / 2019 /”,但它们仍被归类为“ used_model_core_incentives”。

我也根本无法使用该功能来查看关键字块。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

elif re.search("(?:(?:20)|(?:19))\d{2}", Keyword) is None:

缺少前斜线应该是:

elif re.search("/(?:(?:20)|(?:19))\d{2}/", Keyword) is None:

编辑:

就像@ s3n0一样,您确定Keyword是字符串吗?我已经测试了这两种情况,并且在两种情况下都可以执行。