感谢大家的帮助,我完成了这一步,但我有一些新问题,我希望有人能帮助我,我找到了以下you单词,并想用另一个单词替换它们,但此代码仅适用于第一个单词

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])

结果:你突然说了声再见,尽管我非常爱克莱斯,但我"希望"孤独地生活了一百年.

我编辑并突出显示了错误词.

有人能给我一个解决这个问题的办法吗?

推荐答案

您可以使用

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]))

输出:

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 demo.

Details:

  • 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中,则进行替换,否则,将返回找到的匹配.

Python相关问答推荐

Select 用a和i标签包裹的复选框?

Polars LazyFrame在收集后未返回指定的模式顺序

Deliveryter Notebook -无法在for循环中更新matplotlib情节(保留之前的情节),也无法使用动画子功能对情节进行动画

需要计算60,000个坐标之间的距离

在线条上绘制表面

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

基于字符串匹配条件合并两个帧

如何在Python脚本中附加一个Google tab(已经打开)

从spaCy的句子中提取日期

如何在Python中获取`Genericums`超级类型?

需要帮助重新调整python fill_between与数据点

在Python中计算连续天数

从嵌套极轴列的列表中删除元素

BeatuifulSoup从欧洲志愿者服务中获取数据和解析:一个从EU-Site收集机会的小铲子

PYTHON中的selenium不会打开 chromium URL

如何关联来自两个Pandas DataFrame列的列表项?

解析CSV文件以将详细信息添加到XML文件

try 在单个WITH_COLUMNS_SEQ操作中链接表达式时,使用Polars数据帧时出现ComputeError

将标签与山脊线图对齐

如何在Django查询集中生成带有值列表的带注释的字段?