首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python-regex更改我想要的任何单词

python-regex更改我想要的任何单词
EN

Stack Overflow用户
提问于 2022-06-17 09:27:11
回答 1查看 36关注 0票数 2

感谢大家的帮助,我走到了这一步,但我有一些新的问题,我希望有人能帮助我,我找到了下面的单词,我想用另一个词取代他们,但这段代码只适用于第一个单词

代码语言:javascript
复制
import Re
text = 'Suddenly you said goodbye, even though I was passionately in love with you, I hope you stay lonely and live for a hundred years'
def replace(text,key,value,NumberL):
    matches = list(re.finditer(key,text,re.I))
    for i in NumberL:
        newT = matches[i-1]
        text = text[:newT.start(0)] + value + text[newT.end(0):]
    print(text)
replace(text,'you','Cleis',[2,3])

结果:你突然说再见了,虽然我热情洋溢地爱上了克莱斯,但我的“希望救世主”却孤独地生活了一百年。

我编辑并高亮显示了错误的单词。

有人能帮我解决这个问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-17 09:42:21

您可以使用

代码语言:javascript
复制
import re

def repl(m, value, counter, NumberL):
    counter.i += 1
    if counter.i in NumberL:
        return value
    return m.group()

def replace(text,key,value,NumberL):
    counter = lambda x: None
    counter.i = 0
    return re.sub(rf"(?!\B\w){re.escape(key)}(?<!\w\B)", lambda m: repl(m, value, counter, NumberL), text)
    
text = 'Suddenly you said goodbye, even though I was passionately in love with you, I hope you stay lonely and live for a hundred years'
print(replace(text,'you','Cleis',[2,3]))

输出:

代码语言:javascript
复制
Suddenly you said goodbye, even though I was passionately in love with Cleis, I hope Cleis stay lonely and live for a hundred years

Python演示

详细信息

  • counter = lambda x: None设置一个计数器对象,counter.i = 0i属性设置为0
  • re.sub(rf"(?!\B\w){re.escape(key)}(?<!\w\B)", lambda m: repl(m, value, counter, NumberL), text)查找作为一个单词搜索的所有key (说明key中的任何特殊字符),并将其替换为repl函数。
  • repl函数中,counter.i是递增的,如果发现的匹配在NumberL中,则替换发生,否则,返回找到的匹配。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72657189

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档