Python Forum
How do you replace a word after a match from a list of words in each line of a file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do you replace a word after a match from a list of words in each line of a file?
#2
Hello vijjuu,

there are so many stars in your output because this line of code returns nothing and every character is then a match

list1 = re.compile(r'%s\s+((?:\w+(?:\s+!$)) {1})' %checkWords[i]).findall(line)
There must be way better ways of doing this, but this code gives the output you were asking for:

f1=open('testinput.txt', 'r')
f2=open('testoutput.txt', 'w')
checkWords = ["Manager","Director"]
repWords = ("*")
 
for line in f1:
    words = line.split(" ")
    for i in range(len(words)):
        for checkword in checkWords:
            if words[i] == checkword:
            	words[i+1] = repWords
    newline = ""
    for word in words:
        newline = newline + word + " "
    print(newline)
    f2.write(newline)
f1.close()
f2.close()
Output:
This is Manager * speaking.Hello, how are you? I am Fine. this is Director * Nice to Meet you Manager *
Problems: It does not "understand" what a word is, so if punctuation symbols are involved (in the matched word or in the replacement) it fails.
Reply


Messages In This Thread
RE: How do you replace a word after a match from a list of words in each line of a file? - by baquerik - Oct-17-2019, 03:04 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Replace a text/word in docx file using Python Devan 4 3,461 Oct-17-2023, 06:03 PM
Last Post: Devan
  Function to count words in a list up to and including Sam Oldman45 15 6,615 Sep-08-2023, 01:10 PM
Last Post: Pedroski55
  Need to replace a string with a file (HTML file) tester_V 1 775 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,586 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  Working with Excel and Word, Several Questions Regarding Find and Replace Brandon_Pickert 4 1,570 Feb-11-2023, 03:59 PM
Last Post: Brandon_Pickert
  Getting last line of each line occurrence in a file tester_V 1 875 Jan-31-2023, 09:29 PM
Last Post: deanhystad
  Replace columns indexes reading a XSLX file Larry1888 2 996 Nov-18-2022, 10:16 PM
Last Post: Pedroski55
  Need to match two words in a line tester_V 2 877 Nov-18-2022, 03:13 AM
Last Post: tester_V
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,387 Sep-27-2022, 01:38 PM
Last Post: buran
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,622 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020