繁体   English   中英

在Python中循环浏览文件

[英]Looping through file in Python

我对使用Python和Twitter API还是相当陌生。 我有一个文本文件,其格式为每行具有一个或多个Twitter句柄的示例(例如:nameOne nameTwo nameThree)

为了清楚起见,假设我们正在专门讨论此行。 目标是创建一个循环遍历每一行的程序,并打印出名字(nameOne)的关注者和推文以及名字与每个后续名字之间的关系(nameOne和nameTwo之间的关系以及nameOne和nameThree,但在nameTwo和nameThree之间不是必须的)。

这是我到目前为止的代码(在使用代码顶部的访问Twitter API所必需的身份验证密钥之后):

handles = open('inputResearch.rtf', 'r')

entries = handles.readlines()

#start to read through the files and print out the friend information
for entry in entries:
    friends = entry.rsplit(' ', 1)
    firstName = friends[0]
    temp = friends[1:len(friends)-1]
    print(firstName, " followers are:\n")
    for follower in twitterRest.followers_ids(firstName):
        print (twitterRest.get_user(follower).screen_name)
        print("\n")
    print(firstName, " tweets are:\n")
    for status in twitterRest.user_timeline(firstName):
        print (status.text)
        print("\n")
    if(temp != ""):
        for item in friends:
            x =twitterRest.show_friendship(source_screen_name=firstName, 
            target_screen_name=temp)
            print(firstName, " frienship with ", temp, ":\n", x, "\n")

这是错误回溯:

Traceback (most recent call last):
  File "<ipython-input-8-e07ede25e593>", line 1, in <module>
    runfile('/Users/ekvdg/Desktop/BYU/Research/Python Files/input:output.py', wdir='/Users/ekvdg/Desktop/BYU/Research/Python Files')
  File "/Users/ekvdg/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)
  File "/Users/ekvdg/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "/Users/ekvdg/Desktop/BYU/Research/Python Files/input:output.py", line 35, in <module>
    for follower in twitterRest.followers_ids(firstName):
  File "/Users/ekvdg/anaconda3/lib/python3.6/site-packages/tweepy/binder.py", line 245, in _call
    return method.execute()
  File "/Users/ekvdg/anaconda3/lib/python3.6/site-packages/tweepy/binder.py", line 229, in execute
    raise TweepError(error_msg, resp, api_code=api_error_code)
TweepError: [{'code': 34, 'message': 'Sorry, that page does not exist.'}]

我已经确定在打印出“关注者”之后它马上就中断了,我不知道我使用Twitter API还是使用Python是否有问题。 似乎是什么问题?

并且您确定以其他方式(例如手动)访问该页面时是否存在该页面? 我不知道API,但是从您编写的内容来看,页面确实存在并不明显。 它看起来像一个简单的404,根据twitter的API参考,这正是“代码34”的含义。

无论如何,您迟早都会遇到不存在的帐户。 也许您应该考虑将gets放入try-except语句中,如下所示:

try:
    followers_ids = twitterRest.followers_ids(firstName)
except TweepError:
    # log it, try the next guy or do something else entirely

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM