在views.py中,我从特定用户检索推文,然后将其显示在模板中,该模板有效。
但是,这只是原始文本,即链接不可点击,问题是使它们可点击的最佳方法是什么?
注 1:我所指的链接可以是任何链接,但很可能是 Instagram 链接
注 2:如果可能的话,我什至希望主题标签可点击。
views.py 中的代码
user = twitter.User
tweets = []
statuses = t.GetUserTimeline(user)
for s in statuses:
tweets.append(s.text)
html:
<div class="col2">
<ol class="ol_list">
<h4>Twitter</h4>
{% for tweet in tweets %}
<li>
<p>{{tweet}}</p>
</li>
{% endfor %}
</ol>
</div>
最佳答案
我使用这样的代码来做类似的事情:
def linkify(raw_message):
message = raw_message
for url in url_regex.findall(raw_message):
if url.endswith('.'):
url = url[:-1]
if 'http://' not in url:
href = 'http://' + url
else:
href = url
message = message.replace(url, '<a href="%s">%s</a>' % (href, url))
return message
URL 正则表达式是
url_re = re.compile(r"""
[^\s] # not whitespace
[a-zA-Z0-9:/\-]+ # the protocol and domain name
\.(?!\.) # A literal '.' not followed by another
[\w\-\./\?=&%~#]+ # country and path components
[^\s] # not whitespace""", re.VERBOSE)
此正则表达式更喜欢误报,而不是丢失一些边缘情况。它还匹配尾随的 .
。不过我只是稍后将其删除。哈希标签将需要另一个正则表达式来匹配它们。
类似于:
hashtag_re = re.compile(r"""
\# # a hashmark
[^\s]* # not whitespace repeated""", re.VERBOSE)
关于python - 使检索到的推文中的链接可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18468476/