Python在文件中匹配后替换word

Python在文件中匹配后替换word,python,replace,Python,Replace,我们正在寻找在文件中每行的单词列表中,在每次匹配后替换一个单词 我是山姆经理,你好吗?我很好。这是 汤姆主任。很高兴见到你,山姆经理 预期产出: This is Manager *** speaking.Hello, how are you? I am Fine. this is Director *** Nice to Meet you Manager *** 但是,我现在得到的输出: *** T*** h*** i*** s*** *** i*** s*** *** M*** a**

我们正在寻找在文件中每行的单词列表中,在每次匹配后替换一个单词

我是山姆经理,你好吗?我很好。这是 汤姆主任。很高兴见到你,山姆经理

预期产出:

This is Manager *** speaking.Hello, how are you?
I am Fine. this is Director *** Nice to Meet you Manager *** 
但是,我现在得到的输出:

*** T*** h*** i*** s***  *** i*** s***  *** M*** a*** n*** a*** g*** e*** r***  *** S*** a*** m***  *** s*** p*** e*** a*** k*** i*** n*** g*** .*** H*** e*** l*** l*** o*** ,***  *** h*** o*** w***  *** a*** r*** e***  *** y*** o*** u*** ?***

以下是一种可能的方法:

pre_words = ['Manager', 'Director']
with open('testoutput.txt', 'w') as f0:
    with open('testinput.txt') as f1:
        for line in f1.readlines():
            l = line.split()
            j = ['***' if i>0 and l[i-1] in pre_words else l[i] for i in range(len(l))]
            f0.write(' '.join(j)+'\n')
输出:

This is Manager *** speaking.Hello, how are you?
I am Fine. this is Director *** Nice to Meet you Manager ***

这就是你需要的吗?

效果很好。。知道下面的文本输入失败的原因吗:我是山姆经理。你好,你好吗?金经理,我很好。我是汤姆主任。很高兴见到你经理Sam.Director TimIt失败了,因为在第二行,它将“Sam.Director”解释为一个单词,而不是两个单独的单词。这很公平。知道下面的文本输入失败的原因吗:我是山姆经理。你好,你好吗?金经理,我很好。我是汤姆主任。很高兴见到你,经理山姆。蒂姆主任,因为代码在寻找用空格分隔的单词,在“蒂姆主任”之前没有空格。只需添加一个空格。这不仅是可以理解的,而且是正确的,不像你所做的那样。
This is Manager *** speaking.Hello, how are you?
I am Fine. this is Director *** Nice to Meet you Manager ***
lines=open('testinput.txt', 'r').read().split('\n')

checkWords = ["Manager","Director"]
repWords = "***"

out = []
flag = False

for line in lines:
    line_out = []
    for word in line.split(' '):
        if flag:
            line_out.append(repWords)
            flag = False
        else:
            line_out.append(word)
        if word in checkWords:
            flag=True
    out.append(' '.join(line_out))
with open('testoutput.txt', 'w') as f2:
    f2.write('\n'.join(out))