古腾堡项目使用url访问文本

时间:2020-05-19 18:13:43

标签: python nlp nltk project-gutenberg

我正在尝试从gutenberg项目的url访问文本文件。 因此,我从nltk的书中复制了相同的代码,结果却有所不同。

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]

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

’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'

我认为gutenberg项目中的标题存在问题。您能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

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

尝试:

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")

有关更多信息,请参见this answer