Python正则表达式查找和重新定位单词

2024-04-26 10:20:16 发布

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

已解决


我以前一直在使用console.snips.ai控制台来制作和培训我的助手,但现在我希望在本地自行运行它,而不使用所有其他功能,并且需要更改控制台提供给您的导出文件的格式。它需要从:how tall is [Bill Gates](queryObject) [uncle](relations)更改为how tall is [queryObject](Bill Gates) [relations](uncle),然后可以很容易地将其转换为所需的yaml格式

到目前为止,我已经能够用下面一些非常长的代码来翻转实体-queryObject和实体示例Bill Gates周围的括号类型,但是我正在努力翻转(Bill Gates)[queryObject]的位置,其中有一个最近的括号,Bill GatesqueryObject可以交换,而relationsuncle也可以交换

string_ = "how tall is [Bill Gates](queryObject) [uncle](relations)"

nStr = list(string_)

for i , char in enumerate(nStr):

if char == "[":

    nStr[i] = "{"

if char == "]":

    nStr[i] = "}"

if char == "(":

    nStr[i] = "["

if char == ")":

   nStr[i] = "]"

for j , char in enumerate(nStr):

    if char == "{":

        nStr[j] = "("

    if char == "}":

        nStr[j] = ")"

new = ''.join(nStr)

print(new)

所以这成功地把how tall is [Bill Gates](queryObject) [uncle](relations)变成了how tall is (Bill Gates)[queryObject] (uncle)[relations]

但是我如何用离它最近的[]翻转()的位置

更新

这就是现在发生的事情

enter image description here


Tags: 实体stringifis格式how括号relations
2条回答

参考文献: regex matching any character including spaces

代码:

import re
new = 'how tall is [Bill Gates](queryObject) [uncle](relations)'
result = (re.sub(r'(\[.*?\])(\(.*?\))', r'\2\1', new))
print(result)

将更改:

how tall is [Bill Gates](queryObject) [uncle](relations)

收件人:

how tall is (queryObject)[Bill Gates] (relations)[uncle]

re.sub()与反向引用一起使用:

import re

s = 'how tall is [Bill Gates](queryObject) [uncle](relations)'

result = re.sub(r'\[(.*?)\]\((.*?)\)', r'[\2](\1)', s)

# how tall is [queryObject](Bill Gates) [relations](uncle)

相关问题 更多 >