python匹配字符串并在行尾添加单词

python匹配字符串并在行尾添加单词,python,Python,假设我有一个名为file1.txt的文本文件: Adam male John male Mike male Sue female 我有下面的清单 fullname=['John Smith', 'Sue Hunt'] 我希望能够浏览文本文件,如果其中有任何匹配项,请使用单词find修改该行,输出应如下所示: Adam male John male found Mike male Sue female found 所以我得到了这段代码,但是替换函数没有;似乎不对 f=open(file1.t

假设我有一个名为file1.txt的文本文件:

Adam male
John male
Mike male
Sue female
我有下面的清单

fullname=['John Smith', 'Sue Hunt']
我希望能够浏览文本文件,如果其中有任何匹配项,请使用单词find修改该行,输出应如下所示:

Adam male
John male found
Mike male
Sue female found
所以我得到了这段代码,但是替换函数没有;似乎不对

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')
该函数在本地不起作用:

返回包含所有匹配项的字符串副本

尝试:


这听起来像是一项正在进行的工作,因此我将创建两个
名称
性别
字典,以备将来修改,以后可以查阅,并编写一个新的输出文件,以免损坏源文件

# 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

您永远不会将任何内容写回其他文件。您正在拆分exampledata中不包含的字符。你的名字永远不会出现在你的队伍中,因为它没有被分开。你的替代品永远不会被击中。此外,即使您的
replace
被命中,您仍然忽略了它返回的新字符串。为什么不直接写入文件而不是构建
res
?它似乎不会回写到file@chrissk8er是的,你应该自己加上这个部分
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)
# 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