Created
May 29, 2015 22:52
-
-
Save ikks/57b66778466f49b586d4 to your computer and use it in GitHub Desktop.
Twitter with links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def encode_string_with_links(tweet): | |
"""Only used by the get tweets task | |
""" | |
MENTION_REGEX = re.compile(r'''(@(\w{1,15}\b))''', re.UNICODE) | |
HASHTAG_REGEX = re.compile(r'''(#(\w{1,30}\b))''', re.UNICODE) | |
URL_REGEX = re.compile(r'''((https://|http://)[^ <>'"{}|\\^`[\]]*)''') | |
text = tweet['text'].replace('\n', ' ') | |
if text.endswith(u'\u2026'): | |
# If we ended with ..., then we have to check if we have an image | |
# or url to replace at the end | |
last = text.rindex(u' ') | |
if text[last:].find('://') != -1: | |
if 'media' in tweet['entities']: | |
text = u'{0} {1}'.format( | |
text[:last], | |
tweet['entities']['media'][-1]['url'], | |
) | |
elif tweet['entities']['urls']: | |
text = u'{0} {1}'.format( | |
text[:last], | |
tweet['entities']['urls'][-1]['url'], | |
) | |
else: | |
text = text[:last] | |
elif text[last:].find('@') != -1: | |
if ( | |
'user_mentions' in tweet['entities'] and | |
tweet['entities']['user_mentions'] | |
): | |
text = u'{0} @{1}'.format( | |
text[:last], | |
tweet['entities']['user_mentions'][-1]['screen_name'] | |
) | |
else: | |
text = text[:last] | |
elif text[last:].find('#') != -1: | |
if ( | |
'user_hashtags' in tweet['entities'] and | |
tweet['entities']['user_hashtags'] | |
): | |
text = u'{0} #{1}'.format( | |
text[:last], | |
tweet['entities']['hashtags'][-1]['text'] | |
) | |
else: | |
text = text[:last] | |
else: | |
text = text[:last] | |
return HASHTAG_REGEX.sub( | |
r'<a href="https://twitter.com/hashtag/\2" rel="nofollow" target="_blank">#\2</a>', | |
MENTION_REGEX.sub( | |
r'<a href="https://twitter.com/\2" rel="nofollow" target="_blank">@\2</a>', | |
URL_REGEX.sub( | |
r'<a href="\1" rel="nofollow" target="_blank">\1</a>', | |
text, | |
), | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment