【问题标题】:Not able to get Country of a Tweet - Twython API无法获取推文所在的国家/地区 - Twython API
【发布时间】:2016-03-18 08:52:47
【问题描述】:

我正在使用以下代码收集与某个主题有关的推文,但在我提取的所有推文中,“地点”属性为无。难道我做错了什么?此外,该代码旨在提取现有推文,我不需要流式 API 解决方案,也不需要寻找流式 API 的解决方案:https://www.quora.com/How-can-I-get-a-stream-of-tweets-from-a-particular-country-using-Twitter-API

api =   Twython(consumer_key, consumer_secret, access_key, access_secret)

tweets                          =   []
MAX_ATTEMPTS                    =   200
COUNT_OF_TWEETS_TO_BE_FETCHED   =   10000
in_max_id = sys.argv[1]
next_max_id = ''
for i in range(0,MAX_ATTEMPTS):

    if(COUNT_OF_TWEETS_TO_BE_FETCHED < len(tweets)):
        break # we got 500 tweets... !!

    #----------------------------------------------------------------#
    # STEP 1: Query Twitter
    # STEP 2: Save the returned tweets
    # STEP 3: Get the next max_id
    #----------------------------------------------------------------#

    # STEP 1: Query Twitter
    if(0 == i):
        # Query twitter for data. 
        results    = api.search(q="#something",count='100',lang='en',max_id=in_max_id,include_entities='true',geo= True)
    else:
        # After the first call we should have max_id from result of previous call. Pass it in query.
        results    = api.search(q="#something",include_entities='true',max_id=next_max_id,lang='en',geo= True)

    # STEP 2: Save the returned tweets
    for result in results['statuses']:

        temp = ""
        tweet_text = result['text']
        temp += tweet_text.encode('utf-8') + " "
        hashtags = result['entities']['hashtags']
        for i in hashtags:
            temp += i['text'].encode('utf-8') + " " 
        print result
        #temp += i["place"]["country"] + "\n"
        #output_file.write(temp)




    # STEP 3: Get the next max_id
    try:
        # Parse the data returned to get max_id to be passed in consequent call.
        next_results_url_params    = results['search_metadata']['next_results']
        next_max_id        = next_results_url_params.split('max_id=')[1].split('&')[0]
    except:
        # No more next pages
        break

【问题讨论】:

  • 您遇到错误了吗?如果是,是什么类型的错误?
  • 没有错误。只是“places”属性为空!
  • 根据我的回答编辑您的代码,然后它应该可以正常工作。

标签: python twitter twython


【解决方案1】:

简短的回答是,不,你没有做错任何事。所有place 标签都是空的原因是因为统计上它们不太可能包含数据。只有大约 1% 的推文在其place 标签中有数据。这是因为用户很少在推特上发布他们的位置。默认情况下,位置处于关闭状态。

下载 100 条或更多推文,您可能会找到place 标签数据。

【讨论】:

    【解决方案2】:

    如果place 字段对于您的应用将要处理的所有推文都是必须的,那么您可以将搜索限制在一个地方,以确保所有结果都肯定有它。

    您可以通过设置geocode (latitude,longitude,radius[km/mi]) 参数来做到这一点,将您的搜索限制在一个区域内。

    通过 Twython 提出的此类请求示例如下:

    geocode = '25.032341,55.385557,100mi'
    api.search(q="#something",count='100',lang='en',include_entities='true',geocode=geocode)
    

    【讨论】:

    • 这个答案在技术上是不正确的。此过滤器只是确保结果更有可能分配到位置。
    • 这个答案也不正确,因为search/tweet 实际上确实返回了place 标签。但是,place 标签几乎总是空的。只有大约 1% 的推文在 place 标签中有数据。
    • @Jonas Ive 改写了我的回答。并且它不是“技术上”的错误,这完全取决于应用程序的需求以及您希望如何使用结果。
    【解决方案3】:

    并非所有推文都包含所有字段,如 tweet_text、地点、国家、语言等,

    因此,为避免KeyError,请使用以下方法。修改您的代码,以便在找不到您要查找的key 时,返回默认值。

    result.get('place', {}).get('country', {}) if result.get('place') != None else None
    

    这里,上面一行的意思是“取到键place后搜索键country如果存在,否则返回None

    【讨论】:

    • 感谢您的回答,但正如我所写的那样,没有错误。只是 place 属性为 NONE。所以谢谢,但在这种情况下不会有帮助。
    • 你没有做错什么。您需要获得更多推文。我检查了大约 5 万条推文,但我只能找到一百个“地点”字段,其余的都是“空”。在处理之前检查获取的 JSON。
    【解决方案4】:

    kmario 是对的。大多数推文没有这些信息,但只有一小部分有。进行位置搜索会增加这个机会,例如https://api.twitter.com/1.1/search/tweets.json?q=place%3Acba60fe77bc80469&count=1

      "place": {
        "id": "cba60fe77bc80469",
        "url": "https://api.twitter.com/1.1/geo/id/cba60fe77bc80469.json",
        "place_type": "city",
        "name": "Tallinn",
        "full_name": "Tallinn, Harjumaa",
        "country_code": "EE",
        "country": "Eesti",
        "contained_within": [],
        "bounding_box": {
          "type": "Polygon",
          "coordinates": [
            [
              [
                24.5501404,
                59.3518286
              ],
              [
                24.9262886,
                59.3518286
              ],
              [
                24.9262886,
                59.4981855
              ],
              [
                24.5501404,
                59.4981855
              ]
            ]
          ]
        },
        "attributes": {}
      },
    

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 1970-01-01
      • 2012-11-21
      • 2012-01-11
      • 2012-08-06
      • 1970-01-01
      • 2017-12-23
      • 2013-07-12
      • 1970-01-01
      相关资源
      最近更新 更多