python - 如果字符串段落中的项目属于字符串列表,则删除它们?

标签 python string list replace beautifulsoup

 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:需要一个字符对象缓冲区。我知道这是一个初学者问题,但我该如何解决这个问题?

最佳答案

由于您已经在使用 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,'')

关于python - 如果字符串段落中的项目属于字符串列表,则删除它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32594261/

相关文章:

python - 使用高斯混合模型和 scikit learn 进行多类分类

java - 数据输出流到数组

java - 字符串列表中单词的频率

Java List 接口(interface)方法 : containsAll(Collection<? > c)

python - 向初学者解释 'self' 变量

python - 使用 python 解析 CSV 文件(稍后制作决策树)

python多处理从多处理队列访问数据不读取所有数据

java - 计算字符串中单词出现的次数

java - 如何将句子中字符串的第一个字母大写?

list - 为什么这个列表意味着它在 scala 中还有 3 或 3 个以上的元素