gpt4 book ai didi

python - 如果字符串中的单词位于单词列表中,则替换该单词

转载 作者:行者123 更新时间:2023-11-30 22:27:30 25 4
gpt4 key购买 nike

我有以下字符串:

s = 'in may 1999, nothing really happened, same as in june 1999'

month_set = {'may', 'june', 'july'}

我想将与 month_set 列表中的单词匹配的所有单词替换为单词 month。输出应该类似于

'in month 1999, nothing really happened, same as in month 1999'

for month in month_set:
sentence = s.replace(month, 'date')
print(sentence)

但返回以下内容:

in may 1999, nothing really happened, same as in june 1999
in date 1999, nothing really happened, same as in june 1999
in may 1999, nothing really happened, same as in date 1999

此外,如果上述方法有效,我需要将其应用于一个大的字符串列表,我认为这会使其变慢。

最佳答案

你可以试试这个:

s = 'in may 1999, nothing really happened, same as in june 1999'
month_set = {'may', 'june', 'july'}
final_string = ' '.join("month" if i in month_set else i for i in s.split())

输出:

'in month 1999, nothing really happened, same as in month 1999'

纯正则表达式解决方案:

import re
s = 'in may 1999, nothing really happened, same as in june 1999'
month_set = {'may', 'june', 'july'}
final_string = re.sub('|'.join("(?<=\s){}(?=\s)".format(i) for i in month_set), 'month', s)
print(final_string)
s1 = 'may june mayor'
final_string1 = re.sub('|'.join("((?<=\s)|(?<=^)){}((?=\s)|(?=$))".format(i) for i in month_set), 'month', s1)
print(final_string1)

输出:

'in month 1999, nothing really happened, same as in month 1999'
'month month mayor'

关于python - 如果字符串中的单词位于单词列表中,则替换该单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46898757/

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