为什么从 data = response.read() 中读取 "line" 会得到一个整数?

Why does reading a "line" from data = response.read() give an integer?

我有一些 Python 函数,可以将 url 转换为文本文件并下载('url' 始终是文本文件)。我希望能够逐行解码该文本文件,并将每一行作为字符串添加到字符串列表中。

    def download_index(self, url):
        response = urllib.request.urlopen(url)
        data = response.read()
        listOfStrings = []
        for line in data:
            print(line)
            listOfStrings.append(line)

当我运行这个的时候,'line'是一个整数。 相反,如果我打印 'data',它会打印整个未解码的文本文件。

如果我解码 'data',我无法逐行处理它,因为我删除了告诉它换行符位置的代码。编辑:我一定误解了解码的工作原理。我有这种印象,因为当我尝试解码 'data' 然后逐行处理它时,每个 'line' 都是一个大解码字符串中的单个字符

似乎唯一的方法是逐行检查 'data',解码每一行,然后将它们添加到列表中。但我不能那样做,因为就像我说的,如果我尝试写类似 for line in data 的东西,编译器会告诉我 line 是一个整数。事实上,如果我尝试添加 print(line),我会得到随机整数

When I run this, 'line' is an integer.

当你迭代一个类似文件的对象时,你会得到一行。

当您遍历 bytes 对象时,您会得到单独的字节值。哪些是整数(范围从 0-255,包括在内)。

(您用于循环变量的名称与行为不相关。)

EDIT: I must have misunderstood how decoding works. I was under this impression because when I tried to decode 'data' and then process it line by line, each 'line' was a single character in one large decoded string

同样的事情。当您遍历 str 时,您会得到单独的 Unicode 代码点(在正常情况下,这些代码点在您看来是“字符”)。

It seems like the only way to do this would be to go through 'data' line by line, decode each line, and then add them to the list.

事实上,您可以这样做,而且这是一种合理的方法。诀窍是 而不是 .read() 整个 response ,而是直接迭代 response:

response = urllib.request.urlopen(url)
listOfStrings = []
for line in response:
    # Of course, you need to know and use the actual encoding;
    # this is a guess on my part.
    listOfStrings.append(line.decode('utf-8'))

你也可以在这里使用列表理解:

listOfStrings = [line.decode('utf-8') for line in urllib.request.urlopen(url)]

您可以像这样重构代码:

def download_index(self, url):
        response = urllib.request.urlopen(url)
        listOfStrings = []
        for line in response:
            print(line)
            listOfStrings.append(line)

Python 部分有一些语法糖,可让您直接遍历文件以从中获取每一行文本。通过遍历 data,您将遍历字节串的每个字符并获取单个字符。此代码直接遍历 response 并获取您需要的所有行。