Python заменить слово после совпадения в файле - PullRequest
0 голосов
/ 17 октября 2019

Мы ищем замену слова после каждого совпадения в списке слов для каждой строки в файле

Это говорит менеджер Сэм. Привет, как дела? Я в порядке. это директор Том. Приятно познакомиться, менеджер Сэм.

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

Ответы [ 2 ]

0 голосов
/ 17 октября 2019
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))

Вам это нужно?

0 голосов
/ 17 октября 2019

Вот один из возможных способов сделать это:

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 ***
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...