【问题标题】:How to strip html elements from string in nested list, Python如何从嵌套列表中的字符串中剥离 html 元素,Python
【发布时间】:2022-12-20 21:05:23
【问题描述】:

我决定使用 BeautifulSoup 从 Pandas 列中提取字符串整数。 BeautifulSoup 适用于一个简单的示例,但不适用于 Pandas 中的列表列。我找不到任何错误。你能帮我吗?

输入:

df = pd.DataFrame({
    "col1":[["<span style='color: red;'>9</span>", "abcd"], ["a", "b, d"], ["a, b, z, x, y"], ["a, y","y, z, b"]], 
    "col2":[0, 1, 0, 1],
})

for list in df["col1"]:
    for item in list:
        if "span" in item:
            soup = BeautifulSoup(item, features = "lxml")
            item = soup.get_text()
        else:
            None  

print(df)

期望的输出:

df = pd.DataFrame({
        "col1":[["9", "abcd"], ["a", "b, d"], ["a, b, z, x, y"], ["a, y","y, z, b"]], 
        "col2":[0, 1, 0, 1],
    })

【问题讨论】:

    标签: python html pandas beautifulsoup xml-parsing


    【解决方案1】:

    您正在尝试在系列中使用 for 循环进行迭代,但是在使用 Pandas 时,它更适合使用 apply 函数,并且更简单,如下所示:

    def extract_text(lst):
        new_lst = []
        for item in lst:
            if "span" in item:
                new_lst.append(BeautifulSoup(item, features="lxml").text)
            else:
                new_lst.append(item)
                
        return new_lst
    
    df['col1'] = df['col1'].apply(extract_text)
    

    或者您可以使用列表推导式将其单行化:

    df['col1'] = df['col1'].apply(
        lambda lst: [BeautifulSoup(item, features = "lxml").text if "span" in item else item for item in lst]
    )
    

    【讨论】:

      【解决方案2】:

      这会将 extract_integer 函数应用于 col1 列的每个元素,如果元素包含 "span" 标记,则将原始值替换为提取的整数,否则保持值不变。

      def extract_integer(item):
          if "span" in item:
              soup = BeautifulSoup(item, features = "lxml")
              return soup.get_text()
          return item
      
      df = pd.DataFrame({
          "col1":[["<span style='color: red;'>9</span>", "abcd"], ["a", "b, d"], ["a, b, z, x, y"], ["a, y","y, z, b"]], 
          "col2":[0, 1, 0, 1],
      })
      
      df["col1"] = df["col1"].apply(lambda x: [extract_integer(item) for item in x])
      
      print(df)
      

      输出:

                     col1  col2
      0         [9, abcd]     0
      1         [a, b, d]     1
      2   [a, b, z, x, y]     0
      3   [a, y, y, z, b]     1
      
      

      【讨论】:

        猜你喜欢
        • 2012-09-30
        • 2018-03-16
        • 2021-06-17
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        • 1970-01-01
        • 2020-11-15
        • 2011-11-16
        相关资源
        最近更新 更多