Q:

Making a text file which will contain my list items and applying regular expression to it

I am supposed to make a code which will read a text file containing some words with some common linguistic features. Apply some regular expression to all of the words and write one file which will have the changed words.
For now let's say my text file named abcd.txt has these words
king
sing
ping
cling
booked
looked
cooked
packed

My first question starts from here. In my simple text file how to write these words to get the above mentioned results. Shall I write them line-separated or comma separated?
This is the code provided by user palvarez.
import re
with open("new_abcd", "w+") as new, open("abcd") as original:
    for word in original:
      new_word = re.sub("ing$", "xyz", word)
      new.write(new_word)

Can I add something like -
with open("new_abcd", "w+") as file, open("abcd") as original:
    for word in original:
      new_aword = re.sub("ed$", "abcd", word)
      new.write(new_aword)

in the same code file? I want something like -
kabc
sabc
pabc
clabc
bookxyz
lookxyz
cookxyz
packxyz

PS - I don't know whether mentioning this is necessary or not, but I am supposed to do this for a Unicode supported script Devanagari. I didn't use it here in my examples because many of us here can't read the script. Additionally that script uses some diacritics. eg. 'का' has one consonant character 'क' and one vowel symbol 'ा' which together make 'का'. In my regular expression I need to condition the diacritics.

A:

I think the approach you have with one word by line is better since you don't have to trouble yourself with delimiters and striping.
With a file like this:
king
sing
ping
cling
booked
looked
cooked
packed

And a code like this, using re.sub to replace a pattern:
import re
with open("new_abcd.txt", "w") as new, open("abcd.txt") as original:
    for word in original:
      new_word = re.sub("ing$", "xyz", word)
      new_word = re.sub("ed$", "abcd", new_word)
      new.write(new_word)

It creates a resulting file:
kxyz
sxyz
pxyz
clxyz
bookabcd
lookabcd
cookabcd
packabcd

I tried out with the diacritic you gave us and it seems to work fine:
print(re.sub("ा$", "ing", "का"))
>>> कing

EDIT: added multiple replacement. You can have your replacements into a list and iterate over it to do re.sub as follows.
import re

# List where first is pattern and second is replacement string
replacements = [("ing$", "xyz"), ("ed$", "abcd")]

with open("new_abcd.txt", "w") as new, open("abcd.txt") as original:
    for word in original:
      new_word = word
      for pattern, replacement in replacements:
        new_word = re.sub(pattern, replacement, word)
        if new_word != word:
           break
      new.write(new_word)

This limits one modification per word, only the first that modifies the word is taken.

