【问题标题】:TwythonStreamer accents encoding? - unable to decode response, not valid JSON, with code 200TwythonStreamer 重音编码? - 无法解码响应,无效 JSON,代码 200
【发布时间】:2013-10-15 09:18:54
【问题描述】:

我最近开始使用 Twython 和 twitter API。 auth 处理起来有点麻烦,但现在它可以完美地与我脚本中包含的一个小瓶网络服务器一起工作。

我正在尝试做一些非常简单的事情:使用流过滤器 API 跟踪主题标签。 起初它似乎运行良好,但现在我可以在我的日志中看到许多错误:

Error!
200 Unable to decode response, not valid JSON

它只发生在部分推文上。我认为它可以链接到坐标,但事实并非如此。我刚刚测试过,似乎是由重音(éèêàâ...)编码问题引起的。

我该如何解决这个问题?

我的流媒体代码非常基本:

class QMLStreamer(TwythonStreamer):
    def on_success(self, data):
        if 'text' in data:
            if 'coordinates' in data and data['coordinates'] and 'coordinates' in data['coordinates']:
                tweetlog("[%s](%s) - %s" % (data['created_at'], data['coordinates']['coordinates'], data['text'].encode('utf-8')))
            else:
                tweetlog("[%s] - %s" % (data['created_at'], data['text'].encode('utf-8')))

    def on_error(self, status_code, data):
        print colored('Error !', 'red', attrs=['bold'])
        print status_code, data

【问题讨论】:

    标签: python json twitter stream twython


    【解决方案1】:

    错误发生在您的代码中。你不应该在这里使用.encode()

    这有点违反直觉,但如果on_success() 引发异常,则将调用on_error(),这可能就是这里发生的情况(UnicodeDecodeError)。这就是您看到错误代码 200(“HTTP Ok”)的原因。

    Twython 将数据作为 unicode 对象返回,因此您可以这样做:

    print(u"[%s](%s) - %s" % (data['created_at'], data['coordinates']['coordinates'], data['text']))

    您可能应该在 on_success() 中添加自己的 try...except 块以进行进一步调试。

    另外,我不确定您的 tweetlog() 函数是做什么的,但请注意,如果您使用的是 Windows,print() 可能会在编写一些代码点时遇到问题,因为它会尝试转换为终端的代码页。

    【讨论】:

    • 我发送了一个pull request 关于错误屏蔽问题。
    • 感谢您的明确解释。我只是自己想出来并发布解决方案,但您似乎更快。我删除了您引用的那一行的编码形式,以使其保持 unicode,并将其添加到我的打印/日志记录功能中。它现在就像一个魅力。 :)
    【解决方案2】:

    没有完美的答案,但您可以尝试使用 unicodedata 打印文本的规范化版本:

    import unicodedata
    

    ...

    tweetlog("[%s](%s) - %s" % (data['created_at'], data['coordinates']['coordinates'], unicodedata.normalize('NFD',data['text']).encode('ascii', 'ignore')))
    

    【讨论】:

    • 事情是 JSON 解码发生在 TwythonStreamer 中,这使得它直接调用 on_error 而不是 on_success 当它变成香蕉时......所以当错误时你引用的这条线永远不会被调用出现了。
    猜你喜欢
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2021-09-17
    • 2020-07-30
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多