【问题标题】:parsing unicoded tweet using json python使用 json python 解析 unicode 推文
【发布时间】:2012-03-10 15:10:25
【问题描述】:

有很多关于解析 twitter json 的帖子,但我没有看到解决我的问题。

这是代码

import json

file = open('tweet', 'r')
tweet = file.read()
#{"geo":null,"text":"Lmao!! what time? I dont finish evening cleaning till 5 RT \u201c@some_user: football anyone?.....i wanna have a kickabout :(\u201d"}
#{"geo":null,"text":"Lmao!! what time? I dont finish evening cleaning till 5 RT @some_user: football anyone?.....i wanna have a kickabout :("}
def parseStreamingTweet(tweet):
    try:
        singleTweetJson = json.loads(tweet)
        for index in singleTweetJson:
            if index == 'text':
                print "text : ", singleTweetJson[index]
    except ValueError:
        print "Error ", tweet
        print ValueError
        return

parseStreamingTweet(tweet)

这是测试程序。推文进入流媒体,出于检查目的,我将推文保存在文件中并进行了检查。推特提要有一个经过编辑的部分。

谁能告诉我如何解析单编码的推文。评论中的第一条推文是单码的,第二条不是。首先有错误,在删除uni-code字符串时,解析成功。有什么解决办法?

【问题讨论】:

    标签: python json twitter-feed


    【解决方案1】:

    我认为您的代码有效,错误的原因可能是因为 UnicodeEncodeError 当您尝试将 unicode 值打印到终端时发生。我猜你是在非 unicode 感知终端中调用脚本。相反,如果您打印 unicode 值的 repr,或者(将其写入输出文件)它可能会起作用:

    print "text : ", repr(singleTweetJson[index])
    

    使用通用的捕获所有异常/错误消息隐藏特定异常/错误消息通常也是不好的做法。

    【讨论】:

    • 谢谢!这行得通!但我在支持 unicode 的终端中打印(我使用的是 Netbeans IDE,并且支持 unicode。)并且消息打印在异常中,但不是在数组“文本”中,无论如何它都有效!!!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2015-12-25
    • 1970-01-01
    相关资源
    最近更新 更多