【问题标题】:Split according to ":" in multiple lines多行按“:”分割
【发布时间】:2015-03-31 09:27:04
【问题描述】:

我有一组文件组成如下:

Product: Name
Description: description of product

我只想提取名称和描述的内容,而不提取 'Product:''Description:'。为此,我这样做:

div = re.split('Product:\s+|Description:\s+', contentOfFile)

问题是我得到了一个由 3 个元素组成的表格,而不是 2 个元素,开头有一个 ' ' (空格)。我不知道是否总是考虑空间,因为我只想在这种情况下获得:

["Name","description of product"]

【问题讨论】:

    标签: python regex split


    【解决方案1】:

    让我们简化您的示例。如果我们使用管道而不是您的正则表达式进行拆分会怎样?

    >>> "|a|b".split('|')
    ['', 'a', 'b']
    

    如果字符串以分隔符开头,split 将在返回值中添加一个额外的空元素。现在,在您的情况下,分隔符是一个正则表达式,但同样,您的字符串以与该表达式匹配的内容开头,因此第一个返回的元素是一个空字符串。

    要解决它,您可以跳过第一个元素

    div = re.split('Product:\s+|Description:\s+', contentOfFile)[1:]
    

    【讨论】:

    • 很好的解释,但我不喜欢这个解决方案。它非常依赖于: 之前的文本,我也觉得这有点不干净,因为[1:]
    【解决方案2】:

    你不需要split,使用findall

    >>> re.findall(r":\s+(.*)", a)
    ['Name', 'description of product']
    

    使用此解决方案,您将不会依赖: 之前的文本,因此即使您有:

    SomeText: Name
    BlaBlaBla: description of product
    

    它将提取Namedescription of product。为您的问题编写通用解决方案并尝试考虑未来可能出现的情况是一种很好的做法。

    【讨论】:

      【解决方案3】:

      不使用正则表达式的拆分方法的通用解决方案。

      >>> x = """Product: Name
      Description: description of product"""
      >>> [i.split(':')[1].lstrip() for i in x.split('\n')]
      ['Name', 'description of product']
      

      【讨论】:

        【解决方案4】:

        我认为您可以尝试使用 strip 功能而不是 split... 它也有助于删除空间.. 这里是拆分函数的一个小例子

        str1 = "Product: Name";
        str2 = "Description: description of product";
        print str1.lstrip('Product:, ');
        print str2.lstrip('Description:, ');
        

        输出如下图......

        Name
        description of product
        

        【讨论】:

        • OP 只有一个多行的字符串。
        • 我想你不明白 strip 的工作原理:"Description: Description of product".lstrip('Description:, ') -> 'f product'
        • 这是strip的示例程序...但是当您在实际程序中使用时,它会将“”“”“”程序描述“”“”“””替换为原始描述,我不不要认为实际的描述以“”“”“描述”“”“”开头......所以实际的程序是这样工作的......str1 = "Product: Nvidia gtx650"; str2 = "Description: This is the graphics card develop by the NVIDIA company..";然后你可以应用这个方法......
        猜你喜欢
        • 2011-04-07
        • 2010-10-31
        • 2021-02-23
        • 2020-02-28
        • 1970-01-01
        • 2015-07-06
        • 2015-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多