【问题标题】:Can't remove line breaks from BeautifulSoup text output (Python 2.7.5)无法从 BeautifulSoup 文本输出中删除换行符(Python 2.7.5)
【发布时间】:2014-07-22 03:35:05
【问题描述】:

我正在尝试编写一个程序来解析一系列 HTML 文件并将生成的数据存储在 .csv 电子表格中,这非常依赖于正确位置的换行符。我已经尝试了所有可以找到的方法来从某些文本中去除换行符,但无济于事。相关代码如下所示:

soup = BeautifulSoup(f)
ID = soup.td.get_text()
ID.strip()
ID.rstrip()
ID.replace("\t", "").replace("\r", "").replace("\n", "")
dateCreated = soup.td.find_next("td").get_text()
dateCreated.replace("\t", "").replace("\r", "").replace("\n", "")
dateCreated.strip()
dateCreated.rstrip()
# debug
print('ID:' + ID + 'Date Created:' + dateCreated)

生成的代码如下所示:

ID:
FOO
Date Created:
BAR

同一个程序的这个和另一个问题一直让我陷入困境。帮助会很棒。谢谢。

编辑:想通了,这是一个非常愚蠢的错误。而不是仅仅做

ID.replace("\t", "").replace("\r", "").replace("\n", "")

我应该做的

ID = ID.replace("\t", "").replace("\r", "").replace("\n", "")

【问题讨论】:

  • 尝试打印repr(ID) 以查看其中可能包含哪些字节?否则,也许尝试字符串格式而不是连接?
  • 打印 repr(ID) 和 repr(dateCreated) 给了我 u'\nFOO\n' u'\nBAR\n'。我已经尝试将替换设置为 (u"\n", u"") 但这没有做任何事情。

标签: python text beautifulsoup


【解决方案1】:

您手头的问题是,您期望从返回新值的实际操作中进行就地操作。

ID.strip() # returns the rstripped value, doesn't change ID.
ID = ID.strip() # Would be more appropriate.

您可以使用正则表达式,尽管正则表达式对于这个过程来说是多余的。实际上,特别是如果它是开始和结束字符,只需将它们传递给 strip:

ID = ID.strip('\t\r\n')

【讨论】:

    【解决方案2】:

    BeautifulSoup4 有一个 Stripped Strings 的内部实现

    这些字符串往往有很多额外的空格,您可以使用 .stripped_strings 生成器来删除它们: BS4 Doc stripped_strings

    html_doc="""<div class="path">
        <a href="#"> abc</a>
        <a href="#"> def</a>
        <a href="#"> ghi</a>
    </div>"""
    
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html_doc, "html.parser")
    
    result_list = []
    for s in soup.select("div.path"):
        result_list.extend(s.stripped_strings)
    
    print  " ".join(result_list)
    

    Output: abc def ghi
    

    【讨论】:

      【解决方案3】:

      尽管这个问题已经得到了解答,但我只是想明确一点,没有充分的理由以这种冗长的方式进行替换,您实际上可以这样做:

      import re
      
      ID = re.sub(r'[\t\r\n]', '', ID)
      

      尽管regex 通常是要避免的。

      【讨论】:

        【解决方案4】:

        遇到了这个。其他解决方案看起来很复杂,或者没有完全解决 OP。这个单线工作正常:

        ' '.join(re.split(r'[ \n\t]+',soup.text))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-15
          • 2011-07-01
          相关资源
          最近更新 更多