gpt4 book ai didi

python - 正则表达式查找并替换为字典

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:51 25 4
gpt4 key购买 nike

我有一个由两部分组成的问题。最后,我尝试使用 regex 搜索 $"" 中包含的任何字符串,然后将其替换为字典中的值。这是我拥有的:

import re

# Dictionary to use to replace with later
myDict = {'hand_R_item':'hand_R_node', 'hand_L_item':'hand_L_node', 'hips_item':'hips_node', 'body_item':'body_node'}

# String to process
command = '''objs = [$"hand_R_item", $"hand_L_item", $"hips_item"]
for obj in objs:
cmds.select(add = True)
cmds.parent(obj, $"body_item")
'''

# Find all instances of anything matching $""
regex = re.compile(r'\$\"[\w]*?\"')
allMatches = re.findall(regex, command)

# Replace matches with values from dict
newCommand = command
for match in allMatches:
newCommand = newCommand.replace(match, myDict.get(match[2:-1], '') )
print newCommand

这将输出以下内容,这是想要的:

'objs = [hand_R_node, hand_L_node, hips_node]
for obj in objs:
cmds.select(add = True)
cmds.parent(obj, body_node)'

我的问题主要是看我是否以正确的方式处理这个问题:

  1. r'\$\"[\w]*?\"' 是最好的模式吗?我不太习惯使用正则表达式,所以我不知道我是否遗漏了任何陷阱!
  2. 是否有更有效的方法来替换所有内容而不是循环遍历正则表达式结果?我觉得可能有更优雅的方法。

最佳答案

你可以在这里直接使用re.sub。此外,在您的正则表达式中,您不需要转义引号。 \w 可以在字符类之外:

>>> d = {'hand_R_item':'hand_R_node', 'hand_L_item':'hand_L_node', 'hips_item':'hips_node', 'body_item':'body_node'}
>>> reg = re.compile(r'\$"(\w*?)"')
>>> command = '''objs = [$"hand_R_item", $"hand_L_item", $"hips_item"]
... for obj in objs:
... cmds.select(add = True)
... cmds.parent(obj, $"body_item")
... '''
>>>
>>> # Replace the group 1, with corresponding value from dict
>>> reg.sub(lambda m: d[m.group(1)], command)
'objs = [hand_R_node, hand_L_node, hips_node]\nfor obj in objs:\n cmds.select(add = True)\n cmds.parent(obj, body_node)\n'
>>>

关于python - 正则表达式查找并替换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32931752/

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