I'm currently working on a small program.
The aim of the program is to take an input from a file, edit the file to remove any word containing the letter "l" and then output this into an output file.
The code I have at the moment works, however, it does not remove the word containing the letter "l" just the letter itself.
Here is my code
def my_main(ifile_name, ofile_name):
ifile_name = open(ifile_name, 'r')
ofile_name = open(ofile_name, "w+")
delete_list = ['l']
for line in ifile_name:
for word in delete_list:
line = line.replace(word, "")
ofile_name.write(line)
ifile_name.close()
ofile_name.close()
Thank you
UPDATE
This is what the input file looks like:
The first line never changes.
The second line was a bit much longer.
The third line was short.
The fourth line was nearly the longer line.
The fifth was tiny.
The sixth line is just one line more.
The seventh line was the last line of the original file.
And the output file should look like the following when the code is correct
The first never changes.
The second was a bit much.
The third was short.
The fourth was the.
The fifth was tiny.
The sixth is just one more.
The seventh was the of the.
without seeing what your file is like its hard to tell what exactly to use so if you could update the question that would be great
but currently you are looping through each letter instead of the words... use split() to split the words into a list and change that list then rejoin the words together to have a string without the words that contain your letter
words = ''
with open(ifile_name,"r") as file:
for line in file:
list_of_words = line.split(' ')
for key, word in enumerate(list_of_words):
if 'l' in word:
list_of_words[key] = ''
words += ' '.join(w for w in list_of_words if w != '')
words += '\n'
with open(ofile_name, "w+") as file:
file.write(words)
the nice thing with this is you dont have any issues with white space. you will get a regular string with single spaces
EDIT: as pointed out in the comments a better way to do this (non in memory one for the whole file) is to do it inline
with open(ifile_name,"r") as in_file, open(ofile_name, "w+") as out_file:
for line in file:
list_of_words = line.split(' ')
for key, word in enumerate(list_of_words):
if 'l' in word:
list_of_words[key] = ''
out_file.write(' '.join(w for w in list_of_words if w != ''))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments