[英]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.