- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
7 在命令窗口中运行时我遇到了这个问题。我还更新了 pandas,我仔细检查了所有内容,请帮助我解决这个问题。我有我正在使用的推特数据,这些数据是通过 Tweepy 生成的。
import json
import pandas as pd
import matplotlib.pyplot as plt
tweets_data_path = 'C:/Users/e2sn7cy/Documents/GitHub/twitter_data.txt'
tweets_data = []
tweets_file = open(tweets_data_path, 'r')
for line in tweets_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue
#print len(tweets_data)
#DataFrame
tweets = pd.DataFrame()
#adding columns
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
tweets['lang'] = map(lambda tweet: tweet['lang'], tweets_data)
tweets['country'] = map(lambda tweet: tweet['place']['country'] if tweet['place'] != None else None, tweets_data)
#Adding Charts
tweets_by_lang = tweets['lang'].value_count()
fig, ax = plt.subplots()
ax.tick_params(axis='x', labelsize=15)
ax.tick_params(axis='y', labelsize=10)
ax.set_xlabel('Languages', fontsize=15)
ax.set_ylabel('Number of tweets' , fontsize=15)
ax.set_title('Top 5 languages', fontsize=15, fontweight='bold')
tweets_by_lang[:5].plot(ax=ax, kind='bar', color='red')
错误:
(venv) C:\Users\e2sn7cy\Documents\GitHub\Twitter-App>python twitter_analytics.py
Traceback (most recent call last):
File "twitter_analytics.py", line 25, in <module>
tweets['text'] = map(lambda tweet:tweet['text'] if tweet['text'] else '', tweets_data)
File "twitter_analytics.py", line 25, in <lambda>
tweets['text'] = map(lambda tweet:tweet['text'] if tweet['text'] else '', tweets_data)
KeyError: 'text'
推特数据
{"created_at":"Wed Jun 10 10:01:16 +0000 2015","id":608574643897778176,"id_str":"608574643897778176","text":"D\u00e9couvrez le TOP 10 des plus beaux buts de la Ligue des Champions ! #LDC \n\nVid\u00e9o > http:\/\/t.co\/qrOS6JGBYa http:\/\/t.co\/gSBzkhpdWQ","source":"\u003ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003eTweetDeck\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":18802382,"id_str":"18802382","name":"Football.fr","screen_name":"football_fr","location":"","url":"http:\/\/www.football.fr","description":"Compte Twitter officiel de Football.fr, site d'actualit\u00e9s de Newsweb Lagard\u00e8re Active.","protected":false,"verified":true,"followers_count":15012,"friends_count":1290,"listed_count":165,"favourites_count":30,"statuses_count":19099,"created_at":"Fri Jan 09 14:35:24 +0000 2009","utc_offset":7200,"time_zone":"Paris","geo_enabled":true,"lang":"fr","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/403703872\/h_h_h_h_.png","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/403703872\/h_h_h_h_.png","profile_background_tile":false,"profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/562565984548970496\/ggwgwYbh_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/562565984548970496\/ggwgwYbh_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/18802382\/1433626125","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"LDC","indices":[68,72]}],"trends":[],"urls":[{"url":"http:\/\/t.co\/qrOS6JGBYa","expanded_url":"http:\/\/www.football.fr\/ligue-des-champions\/articles\/ronaldo-messi-benzema-les-10-plus-beaux-buts-de-la-saison-video-668464\/","display_url":"football.fr\/ligue-des-cham\u2026","indices":[86,108]}],"user_mentions":[],"symbols":[],"media":[{"id":608574518903341056,"id_str":"608574518903341056","indices":[109,131],"media_url":"http:\/\/pbs.twimg.com\/media\/CHIXTPKWgAAqSXS.jpg","media_url_https":"https:\/\/pbs.twimg.com\/media\/CHIXTPKWgAAqSXS.jpg","url":"http:\/\/t.co\/gSBzkhpdWQ","display_url":"pic.twitter.com\/gSBzkhpdWQ","expanded_url":"http:\/\/twitter.com\/football_fr\/status\/608574643897778176\/photo\/1","type":"photo","sizes":{"small":{"w":340,"h":226,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":600,"h":400,"resize":"fit"},"large":{"w":900,"h":600,"resize":"fit"}}}]},"extended_entities":{"media":[{"id":608574518903341056,"id_str":"608574518903341056","indices":[109,131],"media_url":"http:\/\/pbs.twimg.com\/media\/CHIXTPKWgAAqSXS.jpg","media_url_https":"https:\/\/pbs.twimg.com\/media\/CHIXTPKWgAAqSXS.jpg","url":"http:\/\/t.co\/gSBzkhpdWQ","display_url":"pic.twitter.com\/gSBzkhpdWQ","expanded_url":"http:\/\/twitter.com\/football_fr\/status\/608574643897778176\/photo\/1","type":"photo","sizes":{"small":{"w":340,"h":226,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":600,"h":400,"resize":"fit"},"large":{"w":900,"h":600,"resize":"fit"}}}]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"fr","timestamp_ms":"1433930476532"}
{"created_at":"Wed Jun 10 10:01:16 +0000 2015","id":608574645676204032,"id_str":"608574645676204032","text":"#Coach Training Manager opportunity with Lawn #Tennis Association http:\/\/t.co\/eLUBYQVJZj","source":"\u003ca href=\"http:\/\/www.hootsuite.com\" rel=\"nofollow\"\u003eHootsuite\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":191782743,"id_str":"191782743","name":"Jump in Sport","screen_name":"jumpinsport","location":"Lausanne, Switzerland ","url":"http:\/\/www.jumpinsport.com\/","description":"We collect the best sports related jobs from top sources around the world and show them all in one place! Follow us for great job opportunities.","protected":false,"verified":false,"followers_count":8279,"friends_count":882,"listed_count":168,"favourites_count":38,"statuses_count":30202,"created_at":"Fri Sep 17 10:18:02 +0000 2010","utc_offset":7200,"time_zone":"Bern","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"DBE9ED","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/215611005\/logo_jump_3_square__4_.jpeg","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/215611005\/logo_jump_3_square__4_.jpeg","profile_background_tile":false,"profile_link_color":"CC3366","profile_sidebar_border_color":"DBE9ED","profile_sidebar_fill_color":"E6F6F9","profile_text_color":"333333","profile_use_background_image":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/1267864780\/logo_jump_3_square__4__normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/1267864780\/logo_jump_3_square__4__normal.jpeg","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"Coach","indices":[0,6]},{"text":"Tennis","indices":[46,53]}],"trends":[],"urls":[{"url":"http:\/\/t.co\/eLUBYQVJZj","expanded_url":"http:\/\/www.jumpinsport.com\/?q=node\/30549","display_url":"jumpinsport.com\/?q=node\/30549","indices":[66,88]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en","timestamp_ms":"1433930476956"}
这是我生成此 Twitter 数据的程序
#Import important methods from tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Definig variables for Twitter Credentials
access_token = "ABC"
access_token_secret = "XYZ"
consumer_key = "A123"
consumer_secret = "Z123"
#StdOut received tweets
class StdOutListener(StreamListener):
def on_data(self,data):
print data
return True
def on_error(self,status):
print status
if __name__ == '__main__':
#Twitter authentication and connection
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#Filter Twitter Streams by Keywords
stream.filter(track=['cricket','football','tennis'])
在此之后,我使用此命令捕获了 txt 文件中的数据
python twitter_streaming.py > twitter_data.txt
最佳答案
做起来没有问题:
import pandas as pd
aux = pd.DataFrame()
aux['text'] = [0, 1, 2]
所以问题出在您的tweet['text']
(在map
函数内):
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
在(至少)您从文件 tweets_data_path
中读取并使用 json
加载的那些行之一中,没有这样的字段 'text'
。
此外,作为旁注,考虑将列表理解作为 map
和 lambda
的替代方法:
array = [{'a': 1, 'b': 2}, {'a': 11, 'b': 22}]
map(lambda x: x['a'], array)
[x['a'] for x in array]
查看最后两行如何输出相同的数组,尽管我个人认为后者更易于阅读。
认为上面的信息足以了解问题出在哪里以及如何自己找到解决方案(在学习编程语言时,我认为边做边学总是更好)。
根据您的要求,这里有一个解决方法:如果行不完整,您可以在从文件加载行时避免将推文附加到 tweets_data
。像这样的东西:
for line in tweets_file:
tweet = json.loads(line)
if not all(x in tweet for x in ['text', 'lang', 'place']):
continue
if tweet['place'] and not 'country' in tweet['place']:
continue
tweets_data.append(tweet)
请注意,代码尚未经过测试。尝试了解它的工作原理并修复它或根据您的需要调整它。
关于python - 在 PYTHON 2.7 中使用 pandas 时出现键盘错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30758495/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!