繁体   English   中英

Python 在文件中匹配后替换单词

[英]Python replace word after a match in a file

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

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

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

预期 Output:

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

但是,Output 我现在得到:

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

Output:

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

这是你需要的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM