【问题标题】:Python: extract all sub-strings in between tags within stringPython:提取字符串内标签之间的所有子字符串
【发布时间】:2016-03-29 21:15:53
【问题描述】:

我有一个大字符串,格式如下:

'324/;.ke5 efwef dwe,werwrf <>i want this<> ergy;'56\45,> thu ;lokr<>i want this<> htur ;''\> htur> jur'

我知道我可以做一些事情:

result= text.partition('<>')[-1].rpartition('<>')[0]

但这只会给我字符串中第一个 和最后一个 之间的内容,我如何遍历整个字符串并提取每个相应 标签对之间的内容?

【问题讨论】:

    标签: python html string parsing tags


    【解决方案1】:

    你可以使用正则表达式和findall():

    >>> import re
    >>> s = "324/;.ke5 efwef dwe,werwrf <>i want this<> ergy;'56\45,> thu ;lokr<>i want this<> htur ;''\> htur> jur"
    >>> re.findall(r"<>(.*?)<>", s)
    ['i want this', 'i want this']
    

    其中(.*?) 是一个捕获组,可以在non-greedy 模式下匹配任意字符任意次数。

    【讨论】:

    • 您好,我厌倦了使用您的方法,起初它有效,但后来我尝试使用它查找“\/\/”标签中的所有内容,但我停止了工作,您知道这是为什么吗? @alecxe
    • @abcla 我认为这可以而且应该有资格作为一个单独的问题。如果您需要帮助,请考虑发布 - 确保提供所有详细信息。要关闭此主题,请考虑接受答案,谢谢。
    【解决方案2】:

    我认为string.split() 是你想要的:

    >>> text = """'324/;.ke5 efwef dwe,werwrf <>i want this<> ergy;'56\45,> thu ;lokr<>i want this<> htur ;''\> htur> jur'"""
    >>> print text.split('<>')[1:-1]
    ['i want this', " ergy;'56%,> thu ;lokr", 'i want this']
    

    split() 方法为您提供了一个字符串列表,其中参数用作分隔符。 (https://docs.python.org/2/library/string.html#string.split) 然后,[1:-1] 为您提供列表的一部分,没有第一个和最后一个元素。

    【讨论】:

      猜你喜欢
      • 2015-06-27
      • 2015-08-01
      • 2012-01-29
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多