I'm trying to:
- iterate over txt file (using split() to work on words only for each line in file)
My goal is to:
- for each word in line: change it during iteration
- for any next line/iteration: change only next (and next...) word.
Currently I have something like this:
input.txt: THIS IS A TEST
Code:
#!/usr/bin/env python3
change_to = 'SSSSSSSS'
fp = open('input1.txt','r')
lines = fp.readlines()
for line in lines:
print("--------------------------------------------")
print("Input line: ", line)
# changing
new_line = line.split(" ")
for i in range(len(new_line)):
new_line[i] = change_to
print(" ".join(new_line))
I tried with iter(), enum() and range() but without any luck.
What should be done to achieve "change next word in each next line we are parsing"?
Thank you for all the hints!
CodePudding user response:
Assumption: I assume you wish to display the line with only one word changed on each iteration of the loop and the position of that word depends on the iteration.
Issues in your code: If my assumption is correct then your code is mostly correct. However, modifying the line each time you iterate through your loop will eventually replace all the words in the line. If you just wish to change one word then create a copy of the line and replace the relevant word in the temporary copy and display it.
You should also remember to close the file.
Solution with issues corrected: The solution below corrects the issues in your code with just a few changes.
change_to = 'SSSSSSSS'
fp = open('input1.txt', 'r')
lines = fp.readlines()
for line in lines:
print("--------------------------------------------")
print("Input line: ", line)
# changing
new_line = line.split()
for i in range(len(new_line)):
tmp = new_line.copy()
tmp[i] = change_to
print(" ".join(tmp))
fp.close()
This will result in the following output:
--------------------------------------------
Input line: THIS IS A TEST
SSSSSSSS IS A TEST
THIS SSSSSSSS A TEST
THIS IS SSSSSSSS TEST
THIS IS A SSSSSSSS
Simplified solution: You can simplify your program as shown below. Note, that the with
keyword will automatically close your file. You can learn more about it here.
change_to = 'SSSSSSSS'
with open('input1.txt') as file:
lines = file.readlines()
for line in lines:
print(f'{"-" * 40}\n{line}')
words = line.split()
for i in range(len(words)):
print(' '.join(words[:i] [change_to] words[i 1:]))