【发布时间】:2013-07-04 10:51:33
【问题描述】:
我编写了一个简单的脚本,它只获取一个网页并将其内容提取到一个标记化列表中。但是,我遇到了一个问题,当我将 BeautifulSoup 对象转换为字符串时,“、”等的 UTF-8 字符不会转换。相反,它们仍保持 unicode 格式。
我在创建 BeautifulSoup 对象时将源定义为 UTF-8,我什至尝试单独运行 unicode 转换,但没有任何效果。有人知道为什么会这样吗?
from urllib2 import urlopen
from bs4 import BeautifulSoup
import nltk, re, pprint
url = "http://www.bloomberg.com/news/print/2013-07-05/softbank-s-21-6-billion-bid-for- sprint-approved-by-u-s-.html"
raw = urlopen(url).read()
soup = BeautifulSoup(raw, fromEncoding="UTF-8")
result = soup.find_all(id="story_content")
str_result = str(result)
notag = re.sub("<.*?>", " ", str_result)
output = nltk.word_tokenize(notag)
print(output)
【问题讨论】:
-
哇,它实际上是这样拼写的。 'fromEncoding' 完全不会与 'formEncoding' 混淆。
-
您可以复制并粘贴您认为无法转换的字符吗?字符 [“] 和 ['] 与 ["] 和 ['] 不同。您是否希望它们以某种方式自动转换?
标签: python utf-8 beautifulsoup nltk