我的问题
当使用tweepy进行流数据传输时,我将收到
Tweet Contents: RT @ChickSoPretty: Zendaya tho \ud83d\ude4c https:....当使用代码时
def on_data(self, data):
username = data.split(',"screen_name":"')[1].split('","location"')[0]
tweet = data.split(',"text":"')[1].split('","source')[0]
print("Tweet Contents: " + tweet)-我目前正在跟踪u'\U0001f64c'__,-一个表情符号的代码.
然而,当我试图输出其他用户最近的推文时.
for status in tweepy.Cursor(api.user_timeline, id=username).items(20):
tweet = status.text
print("Tweet Contents: " + tweet)其中‘用户名’是用户谁最近使用了一个表情符号,我的程序崩溃。
这是可以理解的,因为我现在正尝试在控制台上打印一个表情符号,而不是最初所做的,而是显示Javascript代码\ud83d\ude4c。
我的问题是,如何读取用户的状态并以第一种格式输出他们的tweet?
我代码的目的
我的长期目标是遍历用户的状态,并检查他们在最新的20条推特(包括RT和回复)中使用了多少表情符号。
当表情符号以Javascript/Javascript格式显示时,我已经“成功地创建了”一些混乱的代码来检测tweet中的表情符号,如下所示.
for character in tweet:
iteration = iteration + 1
if(iteration < tweetLength):
if tweet[iteration] == '\\' and tweet[iteration + 1] == 'u' and tweet[iteration + 6] == '\\' and tweet[iteration + 7] == 'u':
for x in range(0,12):
emojiCode += tweet[iteration + x]
numberOfEmojis = numberOfEmojis + 1
print("Emoji Code Found: "+emojiCode)
emojiCode = ""
iteration = iteration + 7哇,真是一团糟。但是,它适用于我需要它做的事情(只有英语推特)。
有更好的办法吗?我应该放弃这个然后使用吗
tweet.encode('utf-8')并试图找到以下输出格式的表情符号?
b'@Jathey3 @zachnahra31 this hard\xf0\x9f\x98\x82 we gotta do this https:...'我正在使用Python 3.4.2
发布于 2016-05-16 23:49:37
有更好的办法吗?
是的:不要尝试使用低级别的逐字符字符串处理JSON格式的数据。标准库中有一些工具可以更快、更可靠地完成这一任务。
搜索一个字符的JSON-string-文字编码形式是很棘手的,因为您不知道它是作为\ud83d\ude4c还是仅仅是原始字符(在庆祝活动中举起双手的U+1F64C人员)。任何其他非表情符号字符也可能被编码为\u转义,例如,\u0061\u0061是aa。当你有双反斜杠或转义引号时,也有一些规则,在寻找字符的同时很难处理,而且当你试图找到你想要的属性时,在属性顺序和空格格式方面也会出现很多问题。
通过使用json模块的loads方法将JSON字符串解码为包含原始字符串的Python字典,可以避免所有这些陷阱。
然后,要在一定范围内查找字符,需要有由re模块提供的正则表达式。
最后,如果您想以\ud83d\ude4c的形式显示JSON格式的输出,可以使用json.dumps方法将输出编码回JSON。
# Assuming input like:
json_input= '{"screen_name":"fred","location":"home","text":"Here is an emoji: ... and here is another one "}'
import json, re
emoji_pattern = re.compile('[\U0001F300-\U0001F64F]')
dict_input = json.loads(json_input)
text = dict_input['text']
screen_name = dict_input['screen_name']
emojis = emoji_pattern.findall(text)
print(len(emojis), 'chars found in post by', screen_name)
for emoji in emojis:
print('emoji: ' + json.dumps(emoji))
2 chars found in post by fred
Character: "\ud83d\ude4c"
Character: "\ud83d\udca9"(这假设只有U+1F300到U+1F64F范围内的字符才算为真正的表情符号。还有其他字符可以被归类为表情符号,但这是另一罐蠕虫。另外,将来的Unicode版本可能会添加更多的新字符。)
(附带注意:在Python3.3之前,\U in re将不适用于“窄”Python构建的用户。)
https://stackoverflow.com/questions/37260807
复制相似问题