gpt4 book ai didi

Python:用 re.sub 替换列表中的多个特定单词

转载 作者:行者123 更新时间:2023-12-01 13:10:18 27 4
gpt4 key购买 nike

我有以下字符串和列表 'changewords'。我想将“{word from list}\n”替换为“{word from list}:”我不想替换“\n”的所有实例。

string = "Foo \n value of something \n Bar \n Another value \n"
changewords = ["Foo", "Bar"]

期望的输出:

'Foo: value of something \n Bar: Another value \n'

我试过以下方法

for i in changewords:
tem = re.sub(f'{i} \n', f'{i}:', string)
tem
Output: 'Foo \n value of something \n Bar: Another value \n'

changewords2 = '|'.join(changewords)
tem = re.sub(f'{changewords2} \n', f'{changewords2}:', string)
tem
Output: 'Foo|Bar: \n value of something \n Foo|Bar: Another value \n'

我怎样才能得到我想要的输出?

最佳答案

您可以使用此代码:

import re

string = "Foo \n value of something \n Bar \n Another value \n"
changewords = ["foo", "Bar"]

tem = string
for i in changewords:
tem = re.sub(f'(?i){i} \n', f'{i}:', tem)
print( tem )

输出:

foo: value of something
Bar: Another value

注意 tem = string 来初始化 tem 值,然后在 for 循环中使用 re.sub on tem 将结果返回给 tem 本身。

使用 (?i) 是为了忽略大小写匹配。

Code Demo

关于Python:用 re.sub 替换列表中的多个特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60513795/

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