Skip to content

Commit 2ea45ab

Browse files
author
ping
committed
Fix html_for_tweet when a hashtag/mention is a substring of another
1 parent 26ea0f3 commit 2ea45ab

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

twython/api.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"""
1111

1212
import warnings
13+
import re
1314

1415
import requests
1516
from requests.auth import HTTPBasicAuth
@@ -550,19 +551,22 @@ def html_for_tweet(tweet, use_display_url=True, use_expanded_url=False):
550551
entities = tweet['entities']
551552

552553
# Mentions
553-
for entity in entities['user_mentions']:
554+
for entity in sorted(entities['user_mentions'],
555+
key=lambda mention: len(mention['screen_name']), reverse=True):
554556
start, end = entity['indices'][0], entity['indices'][1]
555557

556558
mention_html = '<a href="https://twitter.com/%(screen_name)s" class="twython-mention">@%(screen_name)s</a>'
557-
text = text.replace(tweet['text'][start:end],
558-
mention_html % {'screen_name': entity['screen_name']})
559+
text = re.sub(r'(?<!>)' + tweet['text'][start:end] + '(?!</a>)',
560+
mention_html % {'screen_name': entity['screen_name']}, text)
559561

560562
# Hashtags
561-
for entity in entities['hashtags']:
563+
for entity in sorted(entities['hashtags'],
564+
key=lambda hashtag: len(hashtag['text']), reverse=True):
562565
start, end = entity['indices'][0], entity['indices'][1]
563566

564567
hashtag_html = '<a href="https://twitter.com/search?q=%%23%(hashtag)s" class="twython-hashtag">#%(hashtag)s</a>'
565-
text = text.replace(tweet['text'][start:end], hashtag_html % {'hashtag': entity['text']})
568+
text = re.sub(r'(?<!>)' + tweet['text'][start:end] + '(?!</a>)',
569+
hashtag_html % {'hashtag': entity['text']}, text)
566570

567571
# Urls
568572
for entity in entities['urls']:

0 commit comments

Comments
 (0)