【问题标题】:How can I split string between group of word in python?如何在python中的单词组之间拆分字符串?
【发布时间】:2022-01-21 05:13:45
【问题描述】:

如何从这个字符串中拆分出“Value1”和“Value2”?

my_str = '<a href="default.html" target="_top">Value1</a><a href="browser.html" target="_top">Value2</a>'

我尝试这样做,但它不起作用。

my_str = '<a href="default.html" target="_top">Value1</a><a href="browser.html" target="_top">Value2</a>'
for i in my_str:
    i = str(i).split('^<a.*>$|</a>')
    print(i)

【问题讨论】:

  • str.split() 函数不带正则表达式...使用正则表达式模块来使用正则表达式
  • 不要在 html 上使用正则表达式,使用 html 解析器

标签: python regex


【解决方案1】:

如果您希望每个元素都包含整个 html 元素,则此方法有效。

import re
re.sub("(a>)(<a)", "\\1[SEP]\\2", my_str).split("[SEP]")

如果您只想要这些值,请执行此操作

re.findall("\>(.[^<]+)<\/a>", my_str)

【讨论】:

    【解决方案2】:

    如果您想在 html 上进行正则表达式拆分,您也不应该这样做(请参阅上面的 bs4 答案以获得更好的答案)。

    import re
    my_str = '<a href="default.html" target="_top">Value1</a><a href="browser.html" target="_top">Value2</a>'
    split_str = re.findall(r'(?<=>)\w*?(?=<\/a>)', my_str)
    

    【讨论】:

    • 这会产生['', '']
    • 我在进行编辑时没有意识到 OP 正则表达式不起作用。
    【解决方案3】:

    另一种方法是使用清理技术进行提取,将一个字符拆分并删除不需要的值。

    这是我使用的代码

    
    my_str = '<a href="default.html" target="_top">Value1</a><a href="browser.html" target="_top">Value2</a>'
    
    strList = my_str.split('/a>',maxsplit = 2)
    
    for i in strList:
        try:
            print(i.split('>')[1].replace('<',''))
        except IndexError:
            pass
    

    这将为您提供 Value1 和 Value2

    【讨论】:

      【解决方案4】:

      你可以使用bs4.BeautifulSoup:

      from bs4 import BeautifulSoup
      soup = BeautifulSoup(my_str)
      out = [st.string for st in soup.find_all('a')]
      

      输出:

      ['Value1', 'Value2']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-07
        • 1970-01-01
        • 1970-01-01
        • 2012-12-14
        相关资源
        最近更新 更多