【问题标题】:Remove items in string paragraph if they belong to a list of strings?如果它们属于字符串列表,则删除字符串段落中的项目?
【发布时间】:2015-12-12 04:38:59
【问题描述】:
 import urllib2,sys
 from bs4 import BeautifulSoup,NavigableString

 obama_4427_url = 'http://www.millercenter.org/president/obama/speeches/speech-4427'
 obama_4427_html = urllib2.urlopen(obama_4427_url).read()

 obama_4427_soup = BeautifulSoup(obama_4427_html)

 # find the speech itself within the HTML

 obama_4427_div = obama_4427_soup.find('div',{'id': 'transcript'},{'class': 'displaytext'})

 # convert soup to string for easier processing

 obama_4427_str = str(obama_4427_div)

 # list of characters to be removed from obama_4427_str

 remove_char = ['<br/>','</p>','</div>','<div class="indent" id="transcript">','<h2>','</h2>','<p>']
 remove_char


 for char in obama_4427_str:
 if char in obama_4427_str:
     obama_4427_replace = obama_4427_str.replace(remove_char,'')


 obama_4427_replace = obama_4427_str.replace(remove_char,'')

 print(obama_4427_replace)

使用BeautifulSoup,我从上述网站上抓取了奥巴马的一篇演讲。现在,我需要以有效的方式替换一些残留的 HTML。我在remove_char 中存储了我想消除的元素列表。我正在尝试编写一个简单的for 语句,但出现错误:TypeError: expected a character object buffer。这是一个初学者的问题,我知道,但我怎样才能解决这个问题?

【问题讨论】:

    标签: python string list replace beautifulsoup


    【解决方案1】:

    由于您已经使用BeautifulSoup,您可以直接使用obama_4427_div.text 而不是str(obama_4427_div) 来获取格式正确的文本。那么你得到的文本就不会包含任何残留的html 元素等。

    例子-

    >>> obama_4427_div = obama_4427_soup.find('div',{'id': 'transcript'},{'class': 'displaytext'})
    >>> obama_4427_str = obama_4427_div.text
    >>> print(obama_4427_str)
    
    Transcript
    To Chairman Dean and my great friend Dick Durbin; and to all my fellow citizens of this great nation;
    
    With profound gratitude and great humility, I accept your nomination for the presidency of the United States.
    
    Let me express my thanks to the historic slate of candidates who accompanied me on this ...
    ...
    ...
    ...
    Thank you, God Bless you, and God Bless the United States of America.
    

    为了完整起见,为了从字符串中删除元素,我将创建一个要删除的元素列表(如您创建的 remove_char 列表),然后我们可以为列表中的每个元素在字符串上执行 str.replace() .示例 -

    obama_4427_str = str(obama_4427_div)
    remove_char = ['<br/>','</p>','</div>','<div class="indent" id="transcript">','<h2>','</h2>','<p>']
    for char in remove_char:
        obama_4427_str = obama_4427_str.replace(char,'')
    

    【讨论】:

    • 这太棒了 - 谢谢。不过,为了完整起见,我将如何在 for 循环中删除 &lt;br/&gt;&lt;/p&gt; 之类的元素?
    • 有趣的是 2 个不同的用户正试图同时解析同一个奥巴马演讲。 stackoverflow.com/questions/32593031/…
    • @CarterMasterson 更新了一个关于如何在搅拌中进行替换的示例。
    • 哇,这就是它被称为 BeautifulSoup 的原因。我不明白要输入的字符怎么会少 ;-) 非常好。感谢分享。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 2022-12-04
    • 2018-11-05
    • 1970-01-01
    • 2018-11-01
    相关资源
    最近更新 更多