Basically I am trying to replace A with B, I manage to to change the first line, then the two other lines get deleted and it throws an error:
replace_txt = replace_txt[search_txt]
TypeError: string indices must be integers
My text:
A is best
A is cool
A is awesome
My code:
import fileinput
replace_txt = {'A':'B'}
for line in fileinput.input('text1.txt', inplace=True):
for search_txt in replace_txt:
replace_txt = replace_txt[search_txt]
line = line.replace(search_txt, replace_txt)
print(line, end='')
This line
replace_txt = replace_txt[search_txt]
overwrites your lookup dictionary with a string. So the next time round replace_txt
is no longer a dictionary so selecting using [ ]
gives you an error. Call your lookup dictionary something else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.