【问题标题】:How does one strip text between two delimiters including empty lines? [duplicate]如何剥离两个分隔符之间的文本,包括空行? [复制]
【发布时间】:2017-04-13 15:26:51
【问题描述】:

我正在尝试删除这两个分隔符之间的文本:''。我正在阅读电子邮件内容,然后将该内容写入 .txt 文件。这两个分隔符之间有很多垃圾,包括 .txt 文件中的行之间的空格。我该如何摆脱这个?以下是我的脚本从写入 .txt 文件的数据中读取的内容:

 First Name</td>

                <td bgcolor='white' style='padding:5px

 !important;'>Austin</td>

                </tr><tr>

                <td bgcolor='#f9f9f9' style='padding:5px !important;'

 valign='top' width=170>Last Name</td>

以下是我当前用于从 .txt 文件中读取空行的代码:

    # Get file contents
    fd = open('emailtext.txt','r')
    contents = fd.readlines()
    fd.close()

    new_contents = []

    # Get rid of empty lines
    for line in contents:
        # Strip whitespace, should leave nothing if empty line was just       "\n"
        if not line.strip():
            continue
        # We got something, save it
        else:
            new_contents.append(line)

    for element in new_contents:
        print element

这是预期的:

 First Name     Austin      


 Last Name      Jones       

【问题讨论】:

  • 您能否发布您的示例的预期输出?
  • 同上 @Farhan.K ,但添加一些输入/预期/得到 doohickeys(技术术语)
  • 名字奥斯汀姓氏琼斯

标签: python python-2.7 delimiter


【解决方案1】:
markup = '<td bgcolor='#f9f9f9' style='padding:5px !important;'

 valign='top' width=170>Last Name</td>'
soup = BeautifulSoup(markup)
soup.get_text()

你可以使用BeautifulSoup

【讨论】:

    【解决方案2】:

    您应该考虑使用正则表达式和re.sub 函数:

    import re
    print re.sub(r'<.*?>', '', text, re.DOTALL)
    

    即使建议“不要使用自定义解析器解析 HTML” 总是有效的。

    【讨论】:

      【解决方案3】:

      您需要将 line.strip() 的结果分配给一个变量并将其添加到您的其他内容中。否则,您将只保存未剥离的行。

      for line in contents:
      
          line = line.strip()
      
          if not line:
              continue
          # We got something, save it
          else:
              new_contents.append(line)
      

      【讨论】:

        【解决方案4】:

        您似乎正试图从文本中删除所有 HTML 标记。您可以手动完成,但标签可能很复杂,甚至可以使用多行。

        我的建议是使用专门为处理 xml 和 html 而编写的 BeautifulSoup:

        import bs4
        
        # extract content... then
        new_content = bs4.BeautifoulSoup(content, 'html.parser').text
        print new_content
        

        bs4 模块已经过广泛的测试,可以应对许多极端情况并大大减少您自己的代码...

        【讨论】:

        • 我会试试这个。感谢您的意见。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-06
        • 1970-01-01
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 2018-04-19
        • 2023-03-03
        相关资源
        最近更新 更多