古腾堡计划用网址访问文本

问题描述 投票:1回答:1

我想从古腾堡项目的url中访问一个文本文件,因此我从ltk书中复制了同样的代码,结果却不一样。

from urllib import request
url = "http://www.gutenberg.org/files/2554/2554-0.txt"
response = request.urlopen(url)
raw = response.read().decode('utf8')
raw[:75]

这是ltk书上的。当它正常工作时,它应该打印出来。

’The Project Gutenberg EBook of Crime and Punishment, by Fyodor Dostoevsky\r\n’

但是当我在电脑上试着做同样的事情时,出来的却是这样的结果。

'\ufeffThe Project Gutenberg EBook of Crime and Punishment, by Fyodor Dostoevsky\r'

我觉得是古腾堡项目中的标题有问题。你能帮我如何处理这个问题吗?

python nlp nltk project-gutenberg
1个回答
2
投票

URL响应文本似乎是用UTF-8和BOM编码的。

试试吧。

from urllib import request

url = "http://www.gutenberg.org/files/2554/2554-0.txt"

response = request.urlopen(url)
raw = response.read()
text = raw.decode("utf-8-sig")

请看 本回答 更多信息

© www.soinside.com 2019 - 2024. All rights reserved.