gpt4 book ai didi

python - 如何将普通引号转换为 Guillemets(法语引号),标签除外

转载 作者:行者123 更新时间:2023-11-28 19:29:59 29 4
gpt4 key购买 nike

假设我们有以下文本:

<a href="link">some link</a> How to transform "ordinary quotes" to «Guillemets»

需要的是将其转化为

<a href="link">some link</a> How to transform «ordinary quotes» to «Guillemets»

使用正则表达式和 Python。

我试过了

import re

content = '<a href="link">some link</a> How to transform "ordinary quotes" to «Guillemets»'

res = re.sub('(?:"([^>]*)")(?!>)', '«\g<1>»', content)

print(res)

但是,正如@Wiktor Stribiżew 所注意到的,如果一个或多个标签具有多个属性,这将不起作用,所以

<a href="link" target="_blank">some link</a> How to transform "ordinary quotes" to «Guillemets»

将转化为

<a href=«link" target=»_blank">some link</a> How to transform «ordinary quotes» to «Guillemets»

更新

请注意文字

  • 可以是html,即:

<div><a href="link" target="_blank">some link</a> How to transform "ordinary quotes" to «Guillemets»</div>

  • 不能是html,即:

How to transform "ordinary quotes" to «Guillemets»

  • 不能是html,但可以包含一些html标签,即

<a href="link" target="_blank">some link</a> How to transform "ordinary quotes" to «Guillemets»

最佳答案

手上拿着锤子,什么都像钉子。您不必使用正则表达式。一个简单的状态机就可以了(假设 <> 里面的任何东西都是一个 HTML 标签)。

# pos - current position in a string
# q1,q2 - opening and closing quotes position
s = ' How to transform "ordinary quotes" to «Guillemets» and " more <div><a href="link" target="_blank">some "bad" link</a>'
sl = list(s)
q1, q2 = 0, 0
pos = 0
while 1:
tag_open = s.find('<', pos)
q1 = s.find('"', pos)
if q1 < 0:
break # no more quotation marks
elif tag_open >= 0 and q1 > tag_open:
pos = s.find('>', tag_open) # tag close
elif (tag_open >= 0 and q1 < tag_open) or tag_open < 0:
q2 = s.find('"', q1 + 1)
if q2 > 0 and (tag_open < 0 or q2 < tag_open):
sl[q1] = '«'
sl[q2] = '»'
s = ''.join(sl)
pos = q2
else:
pos = q1 + 1
print(s)

解释:

 Scan your string, 
If not inside tag,
find first and second quotation marks,
replace accordingly,
continue scanning from the second quotation marks
Else
continue to end of tag

关于python - 如何将普通引号转换为 Guillemets(法语引号),标签除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55556776/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com