gpt4 book ai didi

Python。通过url读取文件时的文件编码

转载 作者:太空宇宙 更新时间:2023-11-04 04:52:35 25 4
gpt4 key购买 nike

我需要通过 URL 获取文件并返回该文件中字数最多的字符串。这是我的代码:

from urllib.request import urlopen

def wordiest_line(url):
data = urlopen(url)

if data:
max_words = 0
max_line = ""
for line in data.readlines():
#print(line)
the_encoding = "utf-8"
line = line.decode(the_encoding)
line = line.rstrip()
line_words = line.split()
if len(line_words) > max_words:
max_words = len(line_words)
max_line = line

#print("%s to RETURN\n" % max_line)
return max_line

else:
return None

这些是用于测试此功能的一些 URL:

  1. "http://math-info.hse.ru/f/2017-18/dj-prog/lines1.txt "
  2. "http://lib.ru/FOUNDATION/3laws.txt_Ascii.txt "
  3. "http://math-info.hse.ru/f/2017-18/dj-prog/lines2.txt "

对于链接 1 和 3,它工作正常。但是 wordiest_line("http://lib.ru/FOUNDATION/3laws.txt_Ascii.txt")由于文件编码而无法正常工作,有些文本是西里尔文。

我试图定义什么是字符串编码并对其进行解码。这是代码:

from urllib.request import urlopen
import chardet

def wordiest_line(url):
data = urlopen(url)

if data:
max_words = 0
max_line = ""
for line in data.readlines():
#print(line)
the_encoding = chardet.detect(line)['encoding']
line = line.decode(the_encoding)
#print(the_encoding, line)
line = line.rstrip()
line_words = line.split()
if len(line_words) > max_words:
max_words = len(line_words)
max_line = line

#print("%s to RETURN\n" % max_line)
return max_line

else:
return None

现在 wordiest_line("http://lib.ru/FOUNDATION/3laws.txt_Ascii.txt") 失败并出现错误:'charmap' 编解码器无法解码位置 8 中的字节 0xdc:字符映射到未定义

其他 URL 仍然可以正常工作。您对如何修复它有什么建议吗?

最佳答案

如果您必须猜测或修复困惑输入的编码,chardet 库可以成为您的救星。但是,在您的情况下,已提供此信息——至少对于 lib.ru 示例。正如任何运行良好的服务器所期望的那样,纯文本响应的字符集在“Content-Type” header 中指定:

import codecs
from urllib.request import urlopen

def wordiest_line(url):
resp = urlopen(url)
charset = resp.headers.get_content_charset()
textreader = codecs.getreader(charset)(resp)
for line in textreader:
line = line.rstrip()
# continue with tokenising and counting...

注意:我假设您使用的是 Python 3;上面的代码在 Python 2 中不起作用。此外,我建议您在遍历文件的行之前解码内容,假设您不会收到损坏的输入,例如具有不同编码行的严重困惑的文件。

第二个注释:requests库可能会让您为此任务编写更少的样板代码。

第三个注意事项:对于计数单词,line.split() 相当简单。例如,“argue”和“argue”将被视为不同的词,您甚至可能想将“arguing”和“argued”定义为属于同一个词。在这种情况下,您将不得不使用 NLP 库,例如 NLTK 或 SpaCy。

关于Python。通过url读取文件时的文件编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47855686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com