简体   繁体   中英

python match string and add words to end of the line

Suppose I have a below text file called file1.txt:

Adam male
John male
Mike male
Sue female

and I have the below list

fullname=['John Smith', 'Sue Hunt']

I want to be able go though the text file, and if it there is any matching there, amend the line with the word found, output should look like below:

Adam male
John male found
Mike male
Sue female found

so I got this code, but the replace function don;t seem to be right

f=open(file1.txt,'a')
for line in f:
    for name in fullname:
        firstname,lastname=name.split('--')
        if firstname in line:
            line.replace('\n', 'found\n')

The replace function doesn't work inplace :

Return a copy of the string with all occurrences...

line = line.replace('\n', 'found\n')

Try:

fullname=['John Smith', 'Sue Hunt']
fname = [i.split()[0] for i in fullname]
res = []
with open(filename) as infile:
    for line in infile:
        if line.split()[0] in fname:
            res.append("{} Found \n".format(line.strip()))
        else:
            res.append(line)

with open(filename, "w") as outfile:
    for line in res:
        outfile.write(line)

This sounds like a work in progress, so I'd prepare for future modifications by creating two dictionaries of the names and genders that can be consulted later on and writing a new output file, so as not to corrupt the source file.

# python 3.6+
import re

fullname=['John Smith', 'Sue Hunt']
names = { re.split('\W+', line)[0]:re.split('\W+', line)[1] for line in fullname }

with open('file1.txt', 'r') as f:
    file=f.read().splitlines()
genders = { re.split('\W+', line)[0]:re.split('\W+', line)[1] for line in file }

with open('results.txt', 'w') as f:
         for k,v in genders.items():
              if k in names.keys():
                  f.write(f"{k} {v} found \n")
              else:
                  f.write(f"{k} {v} \n")


cat results.txt
Adam male
John male found
Mike male
Sue female found

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