首页 > 解决方案 > Python在文件中匹配后替换单词

问题描述

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

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

import re
f1=open('testinput.txt', 'r')
f2=open('testoutput.txt', 'w')
checkWords = ["Manager","Director"]
repWords = ("*** ")

for line in f1:
    i = 0
    for i in range(len(checkWords)):
        # Find the next word after the search word
        list1 = re.compile(r'%s\s+((?:\w+(?:\s+!$)) {1})' %checkWords[i]).findall(line)
        checkWords = ','.join(list1)
        print(checkWords)
        line = line.replace(checkWords, repWords)
        print(line)
        f2.write(line)
f1.close()
f2.close()

预期输出:

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*** ?***

标签: pythonreplace

解决方案


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

这是你需要的吗?


推荐阅读