Python dict не возвращает атрибут - PullRequest
1 голос
/ 05 марта 2019

Я пытаюсь получить атрибут 'full_text' для усеченного твита из библиотеки Tweepy. Я могу получить dict, который, кажется, содержит этот ключ. Однако, когда я пытаюсь has_attr проверить этот ключ, или если я получаю доступ к этому ключу, он, кажется, не существует. Если я использую PrettyPrinter, я получаю распечатку объекта, ясно показывая, что там есть атрибут 'full_text'. Я не уверен, почему это не поднято.

Сначала код:

 print("Text: " + str(tweet.text))
 if(tweet.truncated):
            print("Tweet is truncated...")
            if(hasattr(tweet, 'full_text')):
                print("And has a full text attr")
            else:
                print("No full_text attr")

            if(hasattr(tweet, '_json')):
                print("That has json in it")
                print("type: " + str(type(tweet._json)))
                print("Length: " + str(len(tweet._json)))
            else:
                print("No JSON in there, though")

            fullTweet = plex.getFullTweet(tweet)
            print("Got full tweet...")
            if(hasattr(fullTweet, "_json")):
                print("Has _json available")
                print("Type: " + str(type(tweet._json)))
                print("Length: " + str(len(tweet._json)))
                if(hasattr(fullTweet._json, "full_text")):
                    print("Has full text in there: ")
                    print(fullTweet._json['full_text'])
                else:
                   printer.pprint(fullTweet._json)
                    if(hasattr(fullTweet._json, 'full_text')):
                        print("Full text found!")
                        print(fullTweet._json['full_text'])
                    else:
                        print("Didn't get the full text from that")

А вот вывод, который я получаю из усеченного твита:

Text: I had a really bad experience with my psychiatrist yesterday. It’s just amazing how people in power can humiliate m… 
Tweet is truncated...
No full_text attr
That has json in it
type: <class 'dict'>
Length: 23
Got full tweet...
Has _json available
Type: <class 'dict'>
Length: 23
{   'contributors': None,
    'coordinates': None,
    'created_at': 'Tue Mar 05 14:32:29 +0000 2019',
    'display_text_range': [0, 246],
    'entities': {   'hashtags': [],
                    'symbols': [],
                    'urls': [],
                    'user_mentions': []},
    'favorite_count': 514,
    'favorited': False,
    'full_text': 'I had a really bad experience with my psychiatrist '
                 'yesterday. It’s just amazing how people in power can '
                 'humiliate manipulate demean and take advantage of their '
                 'patients. The whole time he was yelling at me I thought “I '
                 'bet he’s a trump supporter”',
    'geo': None,
    'id': 1102939945629560832,
    'id_str': '1102939945629560832',
    'in_reply_to_screen_name': None,
    'in_reply_to_status_id': None,
    'in_reply_to_status_id_str': None,
    'in_reply_to_user_id': None,
    'in_reply_to_user_id_str': None,
    'is_quote_status': False,
    'lang': 'en',
    'place': None,
    'retweet_count': 56,
    'retweeted': False,
    'source': '<a href="http://twitter.com/download/iphone" '
              'rel="nofollow">Twitter for iPhone</a>',
    'truncated': False,
    'user': {   'contributors_enabled': False,
                'created_at': 'Sun Jan 29 18:43:09 +0000 2017',
                'default_profile': False,
                'default_profile_image': False,
                'description': 'Middle Age Mama I say what People Think '
                               '\U0001f928Big on run-on sentences ? I have the '
                               'most Amazing Twitter Friends ?sucker 4 a '
                               'compliment #TheResistance #resist #FBR',
                'entities': {   'description': {'urls': []},
                                'url': {   'urls': [   {   'display_url': 'instagram.com/maydaymindy9',
                                                           'expanded_url': 'http://instagram.com/maydaymindy9',
                                                           'indices': [0, 23],
                                                           'url': ''}]}},
                'favourites_count': 50340,
                'follow_request_sent': False,
                'followers_count': 76027,
                'following': False,
                'friends_count': 60926,
                'geo_enabled': True,
                'has_extended_profile': False,
                'id': 825776310790266883,
                'id_str': '825776310790266883',
                'is_translation_enabled': False,
                'is_translator': False,
                'lang': 'en',
                'listed_count': 144,
                'location': 'East Coast',
                'name': 'Mayday Mindy ?',
                'notifications': False,
                'profile_background_color': '000000',
                'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png',
                'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png',
                'profile_background_tile': False,
                'profile_banner_url': 'https://pbs.twimg.com/profile_banners/825776310790266883/1486309186',
                'profile_image_url': 'http://pbs.twimg.com/profile_images/1091152293033058305/6Ivr9Ghh_normal.jpg',
                'profile_image_url_https': 'https://pbs.twimg.com/profile_images/1091152293033058305/6Ivr9Ghh_normal.jpg',
                'profile_link_color': 'F58EA8',
                'profile_sidebar_border_color': '000000',
                'profile_sidebar_fill_color': '000000',
                'profile_text_color': '000000',
                'profile_use_background_image': False,
                'protected': False,
                'screen_name': 'maydaymindy9',
                'statuses_count': 19555,
                'time_zone': None,
                'translator_type': 'none',
                'url': '',
                'utc_offset': None,
                'verified': False}}
Didn't get the full text from that

Здесь вы можете видеть атрибут 'full_text', вы можете видеть, что это dict и length выглядит правильным, но любая попытка has_attr или доступ к этому элементу в ._json dict ведет себя так, как будто его не существует. Есть идеи, что здесь происходит не так?

1 Ответ

0 голосов
/ 05 марта 2019

Предполагая, что tweet фактически похож на словарь, просто попробуйте if 'full_text' in tweet. 'full_text' представляется словарным ключом, к которому нельзя получить доступ, как к атрибуту самого объекта.

Вот короткая демонстрация

>>> blah = {'a': 2}
>>> hasattr(blah, 'a')
False
>>> 'a' in blah
True

Дело в том, что атрибут и ключ словаря - это не одно и то же. Вот атрибуты этого же словаря:

>>> dir(blah)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

Вы заметите, что ни один из них не является 'a'. С другой стороны, 'a' находится в списке ключей:

>>> blah.keys()
['a']

Когда вы набираете if 'a' in blah, это фактически говорит if 'a' in blah.keys(). Посмотрите документацию по Python, если хотите узнать больше: Python 2 и Python 3

...