【问题标题】:Weird behaviour with len and str.splitlines()len 和 str.splitlines() 的奇怪行为
【发布时间】:2015-05-25 17:48:41
【问题描述】:

我正在使用 requests 库发出 HTTP 请求,并且我想创建一个简单的响应对象来解析我的数据。我遇到的问题如下。将响应对象传递给我的 ApiResponse 时,我将 Response.text 分成几行,对它们进行计数并知道它是多行还是单行。问题是拆分线列表在将 len() 应用于该列表时给了我一个错误,但在控制台中它可以正常工作。

这是课程:

class ApiResponse(object):
pattern = re.compile(r'([a-zA-Z]+): ([a-zA-Z0-9]+)')  # original ([a-zA-Z]+)\: ([a-zA-Z0-9]+)
response_type = ResponseType.OK
response_mode = ResponseMode.SINGLE

def __init__(self, r: resp):
    self.r = r
    self.parse(r)
    self.data = None

def parse(self, r: resp):
    """
    Method that parses the response from the API
    :param r:Response
    """
    if r.status_code != 200:
        self.response_type = ResponseType.ERR

    if len(r.text.splitlines()) > 1:
        self.response_mode = ResponseMode.MULTI

    for line in r.text.splitlines():
        match = self.pattern.search(line)
        if match is None:
            break
        print(match.group(1, 2))  # REMOVE testing
        self.response_type = ResponseType[match.group(1)]

这是控制台输出:

>>> import sys
>>> print(sys.version)
3.4.2 (default, Oct  8 2014, 13:08:17) 
[GCC 4.9.1]
>>> import requests
>>> from clickapy.response import ApiResponse
>>> r = requests.get(API_URL, {'user': USER, 'password': PASS, 'api_id': API_ID})
>>> api_response = ApiResponse(r)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/eefret/PycharmProjects/clickapy/clickapy/response.py", line 32, in __init__
    self.parse(r)
  File "/home/eefret/PycharmProjects/clickapy/clickapy/response.py", line 43, in parse
    if len(r.text.splitlines()) > 1:
TypeError: object of type 'builtin_function_or_method' has no len()
>>> len(r.text.splitlines())
1

为什么会这样?这对我来说没有意义,我正在执行相同的代码,欢迎任何帮助或反馈。

【问题讨论】:

  • 不要将isis not 与数字一起使用!不要将类属性用作预定义的实例属性。
  • 不相关但应该是if r.status_code != 200:
  • 已更正,但仍在做同样的事情
  • 这是从实际的解释器输出中复制粘贴过来的,对吧?因为到目前为止,最可能的解释是代码实际上是len(r.text.splitlines)。检查response.pyc 文件,如果有则将其删除,然后重新检查response.py 文件以确保该行看起来像您认为的那样。
  • 是否只发生在需要帐户数据的 URL 上,还是您也可以使用 http://google.com 等公共 URL 复制它,以便我们自己尝试?

标签: python string typeerror python-3.4


【解决方案1】:

我的一个朋友(全部归功于 Mariano Garcia)帮助了我,由于他没有 SO 帐户,我将发布解决此问题的方法,我的控制台正在强制执行 utf-8 但是在内部,文本仍然必须进行编码,所以解决这个问题的方法是将这个if len(r.text.splitlines()) &gt; 1: 更改为这个if len(r.text.encode("utf-8").splitlines()) &gt; 1:

完整代码:

class ApiResponse(object):
    pattern = re.compile(r'([a-zA-Z]+): ([a-zA-Z0-9]+)')  # original ([a-zA-Z]+)\: ([a-zA-Z0-9]+)
    response_type = ResponseType.OK
    response_mode = ResponseMode.SINGLE

    def __init__(self, r: resp):
        self.r = r
        self.parse(r)
        self.data = None

    def parse(self, r: resp):
        """
        Method that parses the response from the API
        :param r:Response
        """
        if r.status_code != 200:
            self.response_type = ResponseType.ERR

        if len(r.text.encode("utf-8").splitlines()) > 1:
            self.response_mode = ResponseMode.MULTI

        for line in r.text.splitlines():
            match = self.pattern.search(line)
            if match is None:
                break
            print(match.group(1, 2))  # REMOVE testing
            self.response_type = ResponseType[match.group(1)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2011-10-04
    • 2015-03-16
    • 2017-07-04
    • 2019-02-16
    相关资源
    最近更新 更多