Django在字符串中找到Hashtags,并将其包装在<a>标记中以替换它

2024-09-28 22:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个社交媒体网站,我想启用hashtags。例如,如果用户创建的帖子如下所示:

Summer is gone. #sad #comeback #summer

我想用python替换所有出现的#和以下单词:

Summer is gone. <a href="http://127.0.0.1:8000/c/sad">#sad</a> <a href="http://127.0.0.1:8000/c/comeback">#comeback</a> <a href="http://127.0.0.1:8000/c/summer">#summer</a>

这就是我到目前为止所做的:

    def clean_content(self):
        content = self.cleaned_data.get('content')
        content = profanity.censor(content) # (Unrelated Code)
        arr = re.findall(r"#(\w+)", content)
        replace_ar = []
        for hsh in arr:
            if len(hsh) < 80:
                if Category.objects.filter(name__iexact=hsh):
                    # Old Category, Added This To Category List (Unrelated Code)
                    replace_ar.append(hsh)
                else:
                    # New Category, Created Category, Then Added This To Category List (Unrelated Code)
                    replace_ar.append(hsh)
            else:
                # Don't do anything, hashtag length too long
       # No Idea What To Do With replace_ar. Need help here.

在上面的代码中,我接受html文本输入,并找到所有#{{word}。然后我循环遍历它们,检查是否存在具有该名称的类别。如果有,我只是将其添加到该类别,如果没有,我创建一个类别,然后添加它。在这两种情况下,我将hashtag推送到replace_ar数组

现在我想用一个url替换replace_ar数组中的所有hashtag,就像上面的“Summer is gone”示例中那样。我该怎么做


Tags: httpiscodecontentreplacearhrefsummer
1条回答
网友
1楼 · 发布于 2024-09-28 22:30:40

要用相关类别的url替换hashtags(格式为“#categoryname”):

def clean_content(self):
    content = self.cleaned_data.get('content')
    arr = re.findall(r"#(\w+)", content)
    for hsh in arr:
        if len(hsh) < 80:
            full_hash = '#' + hsh
            if Category.objects.filter(name__iexact=hsh):
                content = content.replace(full_hash, f'<a href="http://127.0.0.1:8000/c/{hsh}/">#{hsh}</a>')
            else:
                content = content.replace(full_hash, f'<a href="http://127.0.0.1:8000/c/{hsh}/">#{hsh}</a>')

请注意,应该使用^{}而不是硬编码url

相关问题 更多 >