Python 用户 ID 到用户名 tweepy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29223454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
User ID to Username tweepy
提问by Amro elaswar
Can someone please tell me how to get one username from one id on tweepy? I have looked everywhere and can't find anything.
有人可以告诉我如何从 tweepy 上的一个 ID 中获取一个用户名吗?我到处找,找不到任何东西。
采纳答案by Juan E.
If you just have a user_id value you need to call the twitter API with the get_user(user_id) method. The returned User object will contain the username under screen_name.
如果您只有一个 user_id 值,则需要使用get_user(user_id) 方法调用 twitter API 。返回的 User 对象将包含 screen_name 下的用户名。
# steps not shown where you set up api
u = api.get_user(783214)
print u.screen_name
If you already have the User object from another API call just look for the screen_name.
如果您已经拥有来自另一个 API 调用的 User 对象,只需查找 screen_name。
回答by saimadhu.polamuri
You can use this code to get user screen name or user id
您可以使用此代码获取用户屏幕名称或用户 ID
To get user screen name from user id
从用户 ID 获取用户屏幕名称
In [36]: import tweepy
In [37]: consumer_key = Your_consumerkey
In [38]: consumer_secret = Your_consuersecret
In [39]: access_token = Your_access_token
In [40]: access_token_secret = Your_access_token_secret
In [41]: auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
In [42]: auth.set_access_token(access_token, access_token_secret)
In [43]: api = tweepy.API(auth)
In [48]: user = api.get_user(1088398616)
In [49]: user.screen_name
Out[49]: u'saimadhup'
To get user id from user screen name
从用户屏幕名称中获取用户 ID
In [46]: user = api.get_user(screen_name = 'saimadhup')
In [47]: user.id
Out[47]: 1088398616
回答by kmario23
Although OP clearly needs the username for just one id, in case if one wants to get usernames for a list of ids(<100), then:
尽管 OP 显然只需要一个 id 的用户名,但如果想要获取 id 列表(<100)的用户名,则:
def get_usernames(ids):
""" can only do lookup in steps of 100;
so 'ids' should be a list of 100 ids
"""
user_objs = api.lookup_users(user_ids=ids)
for user in user_objs:
print(user.screen_name)
For larger set of ids, you can just put this in a forloop and call accordingly while obeying the twitter API limit.
对于更大的 id 集,您可以将其放入for循环中并在遵守 twitter API 限制的同时进行相应调用。

