0

I have a the text of a book in txt format.

If a word is contained in specific_words_dict dictionary, I would like to replace that word with word_1 (cat with cat_1). I wrote this code, but it doesn't replace the word in the file.

for filename in os.listdir(path):
    with open(path+"/"+filename,'r+') as textfile:
        for line in textfile:
            for word in line.split():
                if(specific_words_dict.get(word) is not None):
                    textfile.write(line.replace(word,word+"_1"))

What am I doing wrong?

2 Answers 2

3

Don't read and write to a file at the same time. It won't end well. I think at the moment you're appending to the file (so all your new lines are going to the end).

If the file is not too big (it probably won't be), I'd read the whole thing into ram. Then you can edit the list of lines, before rewriting the whole file. Not efficient, but simple, and it works.

for filename in os.listdir(path):
    with open(os.path.join(path, filename)) as fr:
        lines = fr.read().splitlines()
    for index, line in enumerate(lines):
        for word in line.split():
            if specific_words_dict.get(word) is not None:
                lines[index] = line.replace(word, word + "_1")
    with open(os.path.join(path, filename), 'w') as fw:
        fw.writelines(lines)
Sign up to request clarification or add additional context in comments.

3 Comments

missed an if statement under the second for loop
@FHTMitchell It works, but I would like to replace in the text every word that is in the dictionary and not just one.
Good point, I've fixed my answer. This is what happens when you try and code without running it :p
2

Write in other file In addition, you can check if your word is in uppercase or lower case in your dict or in your files. It is maybe why "replace" doesn't work.

for filename in os.listdir(path):
    with open(path+"/"+filename,'r+') as textfile, open(path+"/new_"+filename,'w') as textfile_new:
        for line in textfile:
            new_line = line
            for word in line.split():
                if(specific_words_dict.get(word) is not None):
                 new_line = new_line.replace(word,word+"_1")
            textfile_new.write(new_line)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.