【发布时间】:2015-12-14 16:42:18
【问题描述】:
import urllib2,sys
from bs4 import BeautifulSoup,NavigableString
from string import punctuation as p
# URL for Obama's presidential acceptance speech in 2008
obama_4427_url = 'http://www.millercenter.org/president/obama/speeches/speech-4427'
# read in URL
obama_4427_html = urllib2.urlopen(obama_4427_url).read()
# BS magic
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'})
# obama_4427_div.text.lower() removes extraneous characters (e.g. '<br/>')
# and places all letters in lowercase
obama_4427_str = obama_4427_div.text.lower()
# for further text analysis, remove punctuation
for punct in list(p):
obama_4427_str_processed = obama_4427_str.replace(p,'')
obama_4427_str_processed_2 = obama_4427_str_processed.replace(p,'')
print(obama_4427_str_processed_2)
# store individual words
words = obama_4427_str_processed.split(' ')
print(words)
长话短说,我有奥巴马总统的演讲,我希望删除所有标点符号,这样我就只剩下单词了。我已经导入了 punctuation 模块,运行了一个 for 循环,它并没有删除我所有的标点符号。我在这里做错了什么?
【问题讨论】:
-
否,
str.replace()仅替换 文字。 -
for punct in list(p):你从不使用punct
标签: python string list replace beautifulsoup