【问题标题】:How to modify a long paragraph string and insert html tags into it based on a list of modifiers?如何根据修饰符列表修改长段落字符串并在其中插入html标签?
【发布时间】:2021-07-25 01:34:16
【问题描述】:

我正在使用 Python 后端和 prismic.io CMS 来创建博客。

当我调用 Prismic API 时,我会收到包含内容的 JSON 响应。

对于段落类型的内容,Prismic 的响应方式如下:

段落修饰符位于具有 start、end、type 和 data 属性的 span 内。

我现在正在尝试解析这个,以便我可以在后端呈现 html。为此,我需要获取跨度列表中的每个项目,并修改原始段落字符串。

我开始为此使用 BeautifulSoup(),但是我有点迷茫。我正在尝试回答以下问题:

如何将基于起始位置和结束位置的每个 span 元素的 HTML 标记插入到原始段落文本字符串中,同时考虑到可能存在重叠元素?

以下是我开始编写的代码,但我认为我没有正确解决问题。我可以使用一些更智能的字符串替换或标签插入逻辑吗?

    def parse(self):
        soup = BeautifulSoup()
        
        for item in self.prismic_data:
            if item['type'] == 'paragraph':
                text = item['text']
                new_tag = Tag(name="p", attrs = {"class": "paragraph"})
                if len(item['spans'] > 0):
                    for span in item['spans']:
                        if span['type'] == 'hyperlink':
                            url = span['data']['url']
                            modified_text = text[span['start']:[span['end']]]
                            a_tag = f'<a href="{url}">{modified_text}</a>'
                            # Unfinished logic
                
                new_tag.string = text
                soup.append(new_tag)
        
        return str(soup)   

【问题讨论】:

  • 我不在 python 世界工作,所以我可能完全不合适,但他们(primsic)通常没有工具包来帮助渲染这些东西。检查以下资源:1> github.com/prismicio/python-kit 或 2> 你可以在这里寻求帮助:community.prismic.io
  • 谢谢@Archer11。不幸的是,Prismic python 库的文档记录很差,很难使用。对于我的用例,我发现编写自己的代码来连接到 Prismic 并解析返回的内容更容易。我只是在这里的这个精确部分有点挣扎。

标签: python html beautifulsoup xmldom prismic.io


【解决方案1】:

因此,HTML 序列化程序功能可以让您做到这一点:https://prismic.io/docs/technologies/html-serializer-javascript

这是它的工作原理:https://github.com/prismicio/prismic-dom/blob/master/src/richtext.js

【讨论】:

  • 感谢@Nounou,但您的链接与 Javascript 相关。我正在寻找 Python 解决方案。此外,Prismic python 库的文档记录很差,因此我发现它几乎无法使用。
猜你喜欢
  • 2020-06-15
  • 2012-01-19
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
相关资源
最近更新 更多