简体   繁体   中英

How to change a specific word in a specific line in a text file

My text file looks like this:

Fjodor Dostojevski|Zlocin i kazna|1866|9788897572657|roman|4500|50|true|   
Dragoslav Mihajlovic|Kad su cvetale tikve|1968|3332221115554|drama|3000|20|true|   
Viliam Sekspir|Hamlet|1600|3214569879878|drama|6500|60|true|

I need to search for the the number like 9788897572657 or 3332221115554 , and if the number is in line, then change word true to false in that line.

Here is some code which will process your lines. For each line in the data, it will:

  1. split the line on the |
  2. check if the field in question is in the sample set
  3. if present, insert false .
  4. put the line back together with a join
  5. add it to the output list

Code:

# build a set of the keys we will look for
looking_for = {"9788897572657", "3332221115554"}

output_data = []
for line in test_data:
    fields = line.split('|')
    if fields[3] in looking_for:
        fields[7] = 'false'
    output_data.append('|'.join(fields))

for line in output_data:
    print(line)

Test Data:

test_data = [x.strip() for x in """
    Fjodor Dostojevski|Zlocin i kazna|1866|9788897572657|roman|4500|50|true|
    Dragoslav Mihajlovic|Kad su cvetale tikve|1968|3332221115554|drama|3000|20|true|
    Viliam Sekspir|Hamlet|1600|3214569879878|drama|6500|60|true|
""".split('\n')[1:-1]]

Produces:

Fjodor Dostojevski|Zlocin i kazna|1866|9788897572657|roman|4500|50|false|
Dragoslav Mihajlovic|Kad su cvetale tikve|1968|3332221115554|drama|3000|20|false|
Viliam Sekspir|Hamlet|1600|3214569879878|drama|6500|60|true|

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM