我对Python相当陌生--尽管我对编程并不陌生。我有这个Python脚本,它可以很好地满足我的需要,但是作为Python的新成员,我只是想看看是否有什么我可以做得更好或者更像Python-esque的东西。我最近把所有这些都转化成你现在看到的--它曾经是一个很长的脚本。现在它被分离成逻辑方法。但我太清楚了,代码总是很干净的。那么,有什么窍门或东西可以改进吗?
附带注意:为了安全目的,我更改了文件路径/Twitter身份验证令牌/etc,但代码的其余部分未被更改。
import tweepy
import pytz
import os
idfile = '/pathtofile/tweet_lastID.txt'
def get_tweets():
'''
Sets up and returns the twitter api.
'''
consumerKey = 'consumerKey'
consumerKeySecret = 'consumerKeySecret'
accessToken = 'accessToken'
accessTokenSecret = 'accessTokenSecret'
auth = tweepy.OAuthHandler(consumerKey, consumerKeySecret)
auth.set_access_token(accessToken, accessTokenSecret)
return tweepy.API(auth).user_timeline('mytwitterhandle', since_id=get_last_id_from_file())
def get_last_id_from_file():
'''
Gets the id of the last downloaded tweet from the id file.
'''
with open(idfile, 'r') as f:
return f.readline().rstrip()
def update_last_id(tweets):
'''
Updates the id file with the latest id.
'''
if not tweets:
return
for tweet in reversed(tweets):
latestID = tweet.id_str
with open(idfile, 'w') as f:
f.write(latestID + '\n')
def write_tweets_to_file(tweets):
'''
Writes the given tweets to the backup file.
'''
if not tweets:
return
doc_path = '/pathtofile/tweets_backup.txt'
with open(doc_path, 'a') as f:
for tweet in reversed(tweets):
f.write('\n'.join(tweet).encode('utf8'))
def format_date(date):
'''
Formats a given date to the format '%-d %b %Y at %-I:%M%p'.
'''
datefmt = '%-d %b %Y at %-I:%M%p'
homeTZ = pytz.timezone('US/Central')
utc = pytz.utc
ts = utc.localize(date).astimezone(homeTZ)
timeString = ts.strftime(datefmt)
timeOfDay = timeString[len(timeString)-2:]
timeString = timeString[:-2]
return timeString + timeOfDay[:-1].lower()
def make_tweet(tweet):
'''
Returns a formatted tweet to be written to the backup file from the given tweet data.
'''
return [format_date(tweet.created_at), tweet.text, '----------\n']
if __name__ == '__main__':
tweets = get_tweets()
new_tweets = []
for tweet in tweets:
new_tweets.extend([make_tweet(tweet)])
write_tweets_to_file(new_tweets)
update_last_id(tweets)发布于 2014-05-19 04:37:09
这个代码比我在这里看到的大多数代码都更“Pythonic”。你确定你只是蟒蛇的初学者吗?
一种建议是在另一个python文件中保持consumerKey、consumerKeySecret、accessToken和accessToken的机密性,并从该文件中导入这些值。如果您这样做,那么当您需要将此代码发送到某个人或上传到任何地方时,您可以不必担心将您的consumerKey、consumerKeySecret、accessToken和accessToken值公之于众。
你的台词有些太长了。我建议您在编写代码时遵循PEP 8标准。
同时,在使用camelcase的整个code.If中保持命名惯例的统一,然后始终遵循camelcase。
我相信你能完成以下任务
for tweet in reversed(tweets):
latestID = tweet.id_str就像这样:
lastID = tweet[0]此外,还将tweet附加到文件中,get_last_id()返回最顶部的tweet id。我觉得那是个虫子。
每个推特都有一堂课会更好。这将使代码更漂亮。
下面是我的实现:github。您可以在将其转换为类时引用它。PS:我的代码也不完美。因此,我也欢迎对我的代码的任何评论,提示。
https://codereview.stackexchange.com/questions/51100
复制相似问题