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

时间:2019-02-16 09:48:08

标签: python regex python-3.x

已解决


我以前一直使用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

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

使用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)