代码之家  ›  专栏  ›  技术社区  ›  gd13

标记python内的零件文本

  •  4
  • gd13  · 技术社区  · 7 年前

    我有一个半结构化的。txt文件。文件如下所示:

    <tags>
        blabla<text>
                  I want this
             </text>
        blabla<text>
                   And this
               </text>
            bla<text>
                     and this
                </text>blabla
    </tags>
    

    我想在 <text> 标签。我已经设法使用字符串分区和替换来完成这项工作,但我认为它不是非常有效或漂亮。

    这是我的代码:

    with open('collection.txt') as f:
     read_data = f.read()
    
    text1 = read_data.partition("<text>")[2].partition("</text>")[0]
    temp1 = read_data.replace(text1,'').replace('<text>','',1).replace('</text>','',1)
    text2 = temp1.partition("<text>")[2].partition("</text>")[0]
    temp2 = read_data.replace(text2,'').replace('<text>','',2).replace('</text>','',2)
    text3 = temp2.partition("<text>")[2].partition("</text>")[0]
    

    BeautifulSoup、元素树和其他XML解析器无法工作。 对如何改进我的代码有什么建议吗?我试过编译正则表达式,但没有用。

    4 回复  |  直到 6 年前
        1
  •  3
  •   phihag    7 年前

    使用XML解析器,例如 xml.etree ( live demo ):

    import xml.etree.ElementTree as ET
    doc = ET.parse('collection.txt')
    print([el.text.strip() for el in doc.findall('.//text')])
    # output: ['I want this', 'And this', 'and this']
    
        2
  •  1
  •   Martin Evans    7 年前

    您可以按如下方式使用BeautifulSoup来获取所有文本条目:

    from bs4 import BeautifulSoup
    
    with open('collection.txt') as f:
        read_data = f.read()
    
    soup = BeautifulSoup(read_data, 'xml')
    
    for text in soup.find_all('text'):
        print(text.get_text(strip=True))
    

    为您提供:

    I want this
    And this
    and this
    

    你绝对应该 避免 尝试使用正则表达式进行此类解析,因为对于更复杂的示例,它很快就会失败,例如,如果使用注释,如 <!-- </text> --> 在数据中间,应该忽略它。

        3
  •  1
  •   Brett7533    7 年前

    regex是你最好的朋友!


    import re
    
    p = re.compile(r'<text>([^</]*)</text>')
    result = p.findall(data_txt)
    result = [x.strip() for x in result]
    print(result)
    
        4
  •  1
  •   Someone    7 年前
    re.findall('<text>\s*.*\s*</text>', data)
    

    另一种解决方案