首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中准确地用HTML标记包围单词

如何在python中准确地用HTML标记包围单词
EN

Stack Overflow用户
提问于 2021-09-29 13:10:56
回答 1查看 123关注 0票数 3

现在我有了这些变量和它们各自的值。

代码语言:javascript
复制
s = '''
vinyl I had to go to Miami. The size of the ball is huge also the vinyl cutters.
I have a computer and it is only 1.
Another vinyl

vinylDiesel
'''

data =[
"vinyl",
"size",
"vinyl cutters",
"computer",
"1",
"vinyl",
"5"
]

现在,我想要做的是,对于,数据变量中的每个单词,它可以被的“变量中的特定的HTML标记包围。现在请注意,标记在很大程度上取决于我想要的内容,但是对于本例,让我们简单地使用<tag></tag> & <sub></sub>

最初我只想有这样的输出。(见图)

但是之前,我们可以实现图像上的内容,我们需要用正确的 HTML标记包围这些单词。为什么会这样?,这是因为我试图在PYQT5 QTextEdit Widget中显示结果。因为使用HTML是添加一些样式表的方法,所以这就是我要做的。

为了在图像中有这样的结果。我需要帮助,以创建一个程序,将产生这样的输出。

预期输出:

代码语言:javascript
复制
(<tag>vinyl<tag>)<sub>1</sub> I had to go to Miami. The (<tag>size</tag>)<sub>2</sub> of the ball is huge also the (<tag>(<tag>vinyl</tag>)<sub>1</sub> cutters</tag>)<sub>3</sub>.
I have a (<tag>computer</tag>)<sub>4</sub> and it is only (<tag>1</tag>)<sub>5</sub>.
Another (<tag>vinyl<tag>)<sub>1</sub>

(<tag>vinyl</tag>)<sub>1</sub>Diesel

完成之后,我就可以简单地将https://doc.qt.io/qt-5/qtextedit.html小部件的HTML设置为预期输出的代码,然后我们就可以从图像中得到输出。

我已经尝试过了。

代码语言:javascript
复制
import re
s = '''
vinyl I had to go to Miami. The size of the ball is huge also the vinyl cutters.
I have a computer and it is only 1.
Another vinyl

vinylDiesel
'''


data =[
"vinyl",
"size",
"vinyl cutters",
"computer",
"1",
"vinyl",
"5"
]

for i,p in enumerate(data):
    name = p
    html_element_name ="span"
    color = "blue"

    html_attrs={"style": f"color:{color};font-weight: bold;"}

    sub_num = f"<sub style='font-weight:bold;font-size:15px;'>{i+1}</sub>"

    html_start_tag = '('+"<" + html_element_name + " " + " ".join(["%s='%s'" % (k, html_attrs[k]) for k in html_attrs]) + ">"
    html_end_tag = "</" + html_element_name + ">"+')'+sub_num

    to_replace_with = '  '+html_start_tag+f"{name}"+html_end_tag+'  '

    s = re.sub(fr"{name}",to_replace_with, s)


print(s)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-29 13:26:49

您可以使用递归:

代码语言:javascript
复制
def to_tags(s, data, p = []):
   new_s = ''
   while s:
      if (k:=[(i, a) for i, a in enumerate(data, 1) if s.startswith(a) and a not in p]):
         i, sb = max(k, key=lambda x:len(x[-1]))
         new_s += f'(<tag>{to_tags(sb, data, p + [sb])}</tag>)<sub>{i}</sub>'
         s = s[len(sb):]
      else:
         new_s, s = new_s+s[0], s[1:]
   return new_s

print(to_tags(s, data))

输出:

代码语言:javascript
复制
'\n(<tag>vinyl</tag>)<sub>1</sub> I had to go to Miami. The (<tag>size</tag>)<sub>2</sub> of the ball is huge also the (<tag>(<tag>vinyl</tag>)<sub>1</sub> cutters</tag>)<sub>3</sub>.\nI have a (<tag>computer</tag>)<sub>4</sub> and it is only (<tag>1</tag>)<sub>5</sub>.\nAnother (<tag>vinyl</tag>)<sub>1</sub>\n\n(<tag>vinyl</tag>)<sub>1</sub>Diesel\n'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69377077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档