gpt4 book ai didi

python - 在文本中查找和交换出现的地方

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:49 24 4
gpt4 key购买 nike

我有一个包含以下内容的文本文件作为输入:

update dbo.pc set ab_snus = '1' where ab_pb = 'aeiou' and ab_snus = '2'
update dbo.und set und_ben = '' where und_k = 'UB' AND und_ben = 'Bl'
update dbo.pc set ab_snus = '3' where ab_pb = 'aeiou' and ab_snus = '4'
update dbo.und set und_ben = '' where und_k = 'PC' AND und_ben = 'Bo'

我想做的是将第一个 ab_snus 数据替换为第二个 ab_snus 数据,以及交换 und_ben 数据,这样输出将是:

update dbo.pc set ab_snus = '2' where ab_pb = 'aeiou' and ab_snus = '1'
update dbo.und set und_ben = 'Bl' where und_k = 'UB' AND und_ben = ''
update dbo.pc set ab_snus = '4' where ab_pb = 'aeiou' and ab_snus = '3'
update dbo.und set und_ben = 'Bo' where und_k = 'PC' AND und_ben = ''

这些列中的大多数可以使用正则表达式 '([a-zA-Z\d]+)' 收集,但对于空列,即 '',我不知所措,禁止使用某种re.finditer(r'\'\'')

'([a-zA-Z\d]+)' 也将匹配 und_k,这是不行的。

import re
text = '''
update dbo.pc set ab_snus = '1' where ab_pb = 'aeiou' and ab_snus = '2'
update dbo.und set und_ben = '' where und_k = 'UB' AND und_ben = 'Bl'
update dbo.pc set ab_snus = '3' where ab_pb = 'aeiou' and ab_snus = '4'
update dbo.und set und_ben = '' where und_k = 'PC' AND und_ben = 'Bo'
'''
matchsnus, matchund = [], []
for match in re.finditer(r'\'([a-zA-Z\d]+)\'', text):
matchsnus.append(match.group(0))
print(matchsnus)

将返回以下输出:['2', 'aeiou', '1', 'Bl', 'UB', '4', 'aeiou', '3', 'Bo', 'PC']。一个合理的方法是找到所有出现的 ab_snusund_ben,将它们附加到它们各自的数组,然后应用一些逻辑来交换匹配 0 与 1、2 与 3等等?

TL;DR:如何交换 ab_snusund_ben 的每一行中的数据?

最佳答案

使用 re.sub() 函数进行两次替换:

import re

text = '''
update dbo.pc set ab_snus = '1' where ab_pb = 'aeiou' and ab_snus = '2'
update dbo.und set und_ben = '' where und_k = 'UB' AND und_ben = 'Bl'
update dbo.pc set ab_snus = '3' where ab_pb = 'aeiou' and ab_snus = '4'
update dbo.und set und_ben = '' where und_k = 'PC' AND und_ben = 'Bo'
'''

text = re.sub(r"(update .+\bab_snus = ')([^']*)(' .+\bab_snus = ')([^']*)'", "\\1\\4\\3\\2'", text)
text = re.sub(r"(update .+\bund_ben = ')([^']*)(' .+\bund_ben = ')([^']*)'", "\\1\\4\\3\\2'", text)

print(text)

输出:

update dbo.pc set ab_snus = '2' where ab_pb = 'aeiou' and ab_snus = '1'
update dbo.und set und_ben = 'Bl' where und_k = 'UB' AND und_ben = ''
update dbo.pc set ab_snus = '4' where ab_pb = 'aeiou' and ab_snus = '3'
update dbo.und set und_ben = 'Bo' where und_k = 'PC' AND und_ben = ''

关于python - 在文本中查找和交换出现的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48537236/

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