现在我有了这些变量和它们各自的值。
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是添加一些样式表的方法,所以这就是我要做的。
为了在图像中有这样的结果。我需要帮助,以创建一个程序,将产生这样的输出。
预期输出:
(<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设置为预期输出的代码,然后我们就可以从图像中得到输出。
我已经尝试过了。
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)发布于 2021-09-29 13:26:49
您可以使用递归:
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))输出:
'\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'https://stackoverflow.com/questions/69377077
复制相似问题