假设我有一个下面的文本文件,名为file1.txt:
Adam male
John male
Mike male
Sue female
我有以下列表
fullname=['John Smith', 'Sue Hunt']
我希望能够遍历文本文件,并且如果那里有任何匹配项,请用找到的单词修改行,输出应如下所示:
Adam male
John male found
Mike male
Sue female found
所以我得到了这段代码,但是replace函数似乎不正确
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')
答案 0 :(得分:1)
答案 1 :(得分:0)
尝试:
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)
答案 2 :(得分:0)
这听起来像是正在进行中的工作,所以我将通过创建names
和genders
的两个字典来准备将来的修改,以便稍后查阅并编写新的输出文件,因此以免破坏源文件。
# 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