gpt4 book ai didi

python - 进行不区分大小写的替换但匹配要替换的单词的大小写的最佳方法?

转载 作者:太空狗 更新时间:2023-10-29 21:38:03 24 4
gpt4 key购买 nike

到目前为止,我已经想出了下面的方法,但我的问题是是否有更短的方法可以得到相同的结果?

我的代码:

input_str       = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
replace_str = "stuff"
replacer_str = "banana"


print input_str
# prints: myStrIngFullOfStUfFiWannAReplaCE_StUfFs

if replace_str.lower() in input_str.lower(): # Check if even in the string
begin_index = input_str.lower().find( replace_str )
end_index = begin_index + len( replace_str )

replace_section = input_str[ begin_index : end_index ]

case_list = []
for char in replace_section: # Get cases of characters in the section to be replaced
case_list.append( char.istitle() )

while len( replacer_str ) > len(case_list):
case_list += case_list

sameCase_replacer_str = "" # Set match the replacer string's case to the replace
replacer_str = replacer_str.lower()
for index in range( len(replacer_str) ):
char = replacer_str[ index ]
case = case_list[ index ]
if case == True:
char = char.title()

sameCase_replacer_str += char

input_str = input_str.replace( replace_section , sameCase_replacer_str )

print input_str
# prints: myStrIngFullOfBaNaNAiWannAReplaCE_BaNaNAs

最佳答案

我会使用这样的东西:

import re

def replacement_func(match, repl_pattern):
match_str = match.group(0)
repl = ''.join([r_char if m_char.islower() else r_char.upper()
for r_char, m_char in zip(repl_pattern, match_str)])
repl += repl_pattern[len(match_str):]
return repl

input_str = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
print re.sub('stuff',
lambda m: replacement_func(m, 'banana'),
input_str, flags=re.I)

示例输出:

myStrIngFullOfBaNaNaiWannAReplaCE_BaNaNas

注意事项:

  • 这处理了不同匹配项具有不同大写/小写组合的情况。
  • 假设替换模式是小写的(无论如何,这很容易改变)。
  • 如果替换模式比匹配长,则使用与模式相同的大小写。

关于python - 进行不区分大小写的替换但匹配要替换的单词的大小写的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9208786/

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