标签: keyerror

密钥存在时的KeyError

使用python和twitter api获取推文对象.

我有一个文件(tweetfile =我的计算机上的.txt文件)和推文,我试图循环对象来获取文本.我用tweetObj.keys()检查了twitter对象,看到键和'text'在那里; 但是,当我尝试使用tweetObj ['text']获取单个文本时,我得到了KeyError:'text'

码:

for line in tweetfile:
    tweetObj = json.loads(line)
    keys =  tweetObj.keys()
    print keys
    tweet = tweetObj['text']
    print tweet
Run Code Online (Sandbox Code Playgroud)

以下是输出:

[u'contributors', u'truncated', u'text', u'in_reply_to_status_id', u'id', u'favorite_count', u'source', u'retweeted', u'coordinates', u'entities', u'in_reply_to_screen_name', u'id_str', u'retweet_count', u'in_reply_to_user_id', u'favorited', u'user', u'geo', u'in_reply_to_user_id_str', u'possibly_sensitive', u'lang', u'created_at', u'filter_level', u'in_reply_to_status_id_str', u'place']
@awe5sauce my dad was like "so u wanna be in a relationship with a 'big dumb idiot'" nd i was like yah shes the bae u feel lmao
[u'delete']
Traceback (most …
Run Code Online (Sandbox Code Playgroud)

python twitter dictionary keyerror

3
推荐指数
1
解决办法
3万
查看次数

Dataframe中的KeyError

我有一个数据框,当我将其导出到csv文件时,它看起来就像我想要的那样.

CompanyName 1   2   3   4   5   6   7   8   9   10  11  12
Company 1   182 270 278 314 180 152 110 127 129 117 127 81
Company 2   163 147 192 142 186 231 214 130 112 117 93  101
Company 3   126 88  99  139 97  97  96  37  79  116 111 95
Company 4   84  89  71  95  80  89  83  88  104 93  78  64
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试从"CompanyName"键中取出时,我得到一个KeyError: 'CompanyName'我怀疑它被覆盖的地方,但我不知道如何解决它.

如果我打印我的数据帧我得到:

pivot_table.head(2)
Out[62]: 
Month                  1    2 …
Run Code Online (Sandbox Code Playgroud)

python dataframe pandas keyerror

3
推荐指数
1
解决办法
2万
查看次数

Python字符串中的"CREATE"导致KeyError与"'class'"

我正在尝试使用"Python-Driver"为Cassandra(一个NoSQL数据库)创建一类命令.您可以使用session.execute()在数据库上运行SQL命令.无论如何,我正在尝试创建一个函数来创建一个键空间.

这是代码:

def createKeySpace(self, title, class_type='SimpleStrategy', replication_factor='3'):
    self.session.execute("CREATE KEYSPACE {} WITH REPLICATION = \
    { 'class' : '{}', 'replication_factor' : {} };\
    ".format(title, class_type, replication_factor))
Run Code Online (Sandbox Code Playgroud)

问题是,如果我尝试使用此功能,我会收到错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "db_commands.py", line 12, in createKeySpace
    ".format('CREATE', title, class_type, replication_factor))
KeyError: " 'class' "
Run Code Online (Sandbox Code Playgroud)

我认为值得注意的是:我注意到=Sublime Text中我的字符串中的符号是红色,而通常的String颜色是黄色.如果我从字符串中取出"CREATE",等号将返回黄色!

这是因为Python已经将CREATE识别为SQL语法,并且不喜欢我用.format()声明String的方式吗?任何帮助都会很棒!:)

python cassandra nosql keyerror

3
推荐指数
1
解决办法
216
查看次数

Python电子邮件机器人Pyzmail / IMAPclient错误

因此,我正在研究一个Python脚本以从电子邮件中提取文本,并按照以下说明进行操作。到目前为止,这是脚本:

import imapclient
import pprint
import pyzmail

mymail = "my@email.com"
password = input("Password: ")

imapObj = imapclient.IMAPClient('imap.gmail.com' , ssl=True)
imapObj.login(mymail , password)
imapObj.select_folder('INBOX', readonly=False)
UIDs = imapObj.search(['SUBJECT Testing'])
rawMessages = imapObj.fetch([5484], ['BODY[]'])
message = pyzmail.PyzMessage.factory(rawMessages[5484]['BODY[]'])
Run Code Online (Sandbox Code Playgroud)

但是我收到此错误:

message = pyzmail.PyzMessage.factory(rawMessages[5484]['BODY[]'])
KeyError: 5484
Run Code Online (Sandbox Code Playgroud)

5484是搜索功能找到的电子邮件的ID。我也尝试过放置UID而不是5484,但这也不起作用。提前致谢!

python imapclient keyerror

3
推荐指数
2
解决办法
1082
查看次数

在没有NoneType错误的情况下访问嵌套dicts的pythonic方法是什么

我有一个深嵌套的dict(从json解码,来自instagram api).我的初始代码是这样的:

caption = post['caption']['text']
Run Code Online (Sandbox Code Playgroud)

但是如果'caption'键或'text'键不存在,那将抛出NoneType或KeyError错误.

所以我想出了这个:

caption = post.get('caption', {}).get("text")
Run Code Online (Sandbox Code Playgroud)

哪个有效,但我不确定它的风格.例如,如果我将此技术应用于我正在尝试检索的更深层次的嵌套属性之一,它看起来非常难看:

image_url = post.get('images',{}).get('standard_resolution',{}).get('url')
Run Code Online (Sandbox Code Playgroud)

有没有更好,更pythonic的方式来写这个?我的目标是检索数据(如果有的话),但如果数据不存在则不会阻止执行.

谢谢!

python dictionary styles nonetype keyerror

2
推荐指数
2
解决办法
1482
查看次数

循环10小时后的KeyError

在15秒循环后,我在下面的脚本中得到以下KeyError,完美地工作了10个小时.为什么一个关键错误只会在每15秒运行10个小时后出现一次?

错误:

Traceback (most recent call last):

  File "C:\venderFix.py", line 33, in <module>

    if j['results']:

KeyError: 'results'
Run Code Online (Sandbox Code Playgroud)

码:

import json
import urllib
from pprint import pprint
import time
from arduino import Arduino

vendtime = 0.2                                           
delayTime = 15                                               
searchTerm = 'happy'                      

A = Arduino('COM3') #This will need to be COM3               
A.output([12]) #Output on pin 12                             

countTweet = 0
#To test Twitter for consistancy 
tweet= 0
noTweet= 0



#the infinate loop
while True:

    #j contains the JSON we load from the …
Run Code Online (Sandbox Code Playgroud)

python keyerror

2
推荐指数
1
解决办法
672
查看次数

如何从KeyError中获取关键信息

有没有办法获得引发 a 的密钥KeyError

或者一般来说,我在哪里可以找到 的属性(如果有)Exception

python exception keyerror

2
推荐指数
1
解决办法
1996
查看次数

如何在ModelAdmin中使用InlinePanel?

我正在建立一个需要使用多个子模型实例创建的模型。我希望能够在管理界面中编辑和创建此模型,所以我要使用添加它ModelAdmin。根据文档,我应该能够根据常规Page类型指定字段/面板。但是,当我添加一个时InlinePanel,会KeyError在相关字段名称上得到一个。

models.py

class Application(models.Model):
    # other fields....

    panels = [MultiFieldPanel([
        FieldPanel('applicant'),
        FieldPanel('position'),
        FieldPanel('cover_letter'),
        FieldPanel('qualifications'),
        InlinePanel('references'),
        FieldPanel('draft'),
    ])]


class Reference(models.Model):

    application = models.ForeignKey(
        Application,
        related_name='references',
        on_delete=models.CASCADE,
        blank=False,
    )

    # other fields....
Run Code Online (Sandbox Code Playgroud)

wagtails_hooks.py

class ApplicationAdmin(ModelAdmin):
    model = Application
    menu_icon = 'mail'
    menu_order = 400
    list_display = # other fields....

modeladmin_register(ApplicationAdmin)
Run Code Online (Sandbox Code Playgroud)

错误

要求网址:http : //127.0.0.1 : 8000/admin/involvement/application/create/

Django版本:1.10.5

异常类型:KeyError

异常值:“引用”

异常位置:/[APPFOLDER]/venv/lib/python3.6/site-packages/wagtail/wagtailadmin/edit_handlers.py init,第627行

我无法确定自己做错了什么。有人能指出我正确的方向吗?

django keyerror wagtail

2
推荐指数
1
解决办法
1065
查看次数

Varargs在Julia中给出了关键错误

请考虑下表:

julia> using RDatasets, DataFrames
julia> anscombe = dataset("datasets","anscombe")
11x8 DataFrame
| Row | X1 | X2 | X3 | X4 | Y1    | Y2   | Y3    | Y4   |
|-----|----|----|----|----|-------|------|-------|------|
| 1   | 10 | 10 | 10 | 8  | 8.04  | 9.14 | 7.46  | 6.58 |
| 2   | 8  | 8  | 8  | 8  | 6.95  | 8.14 | 6.77  | 5.76 |
| 3   | 13 | 13 | 13 | 8  | …
Run Code Online (Sandbox Code Playgroud)

variadic-functions julia keyerror

2
推荐指数
1
解决办法
87
查看次数

如何从字典中随机选择一个项目?

我是一名 Python 初学者,正在尝试制作 21 点游戏,并且不断收到有关此代码的多个关键错误

def rank(rank):
    rank={
        '2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'Jack':10,
       'King':10,'Queen':10,'Ace':1}
    return random.choice(rank)
Run Code Online (Sandbox Code Playgroud)

当我尝试像这样调用函数时发生错误

def draw_card(card):
    card_rank=Card.rank(rank)
    card_suit=Card.suit(suit)
    card={card_suit:card_rank}
    return card
Run Code Online (Sandbox Code Playgroud)

尝试使用“Card”类中的“rank”函数将属性应用于新的“card”变量

python dictionary keyerror

2
推荐指数
1
解决办法
3630
查看次数