python - 使检索到的推文中的链接可点击

标签 python django api twitter hyperlink

在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/

相关文章:

python - 在 Scikit 中加载自定义数据集(类似于 20 个新闻组集)以对文本文档进行分类

python - 无法将帧从相机流式传输到 QML

python - 搜索多个字段django

api - 访问 Metacritic API 和/或 Scraping

c - MongoDB 将截断的浮点值返回到小数点后 6 位

python - 如何检查selenium2library是否添加到RIDE中的robotframework项目

python - 检查字符串是否包含python中的数字/数字/数字

python - django 1.7 迁移文件不能使用用户方法

使用 Jquery 的 Django ajax 'like' 按钮?

java - 为什么短信积分不从我们用 java 编写的短信销售门户上的用户帐户中扣除