假设我有一个名为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
所以我得到了这段代码,但是替换函数似乎并不正确
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')
发布于 2018-07-28 04:39:06
尝试:
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)
发布于 2018-07-28 07:41:29
这听起来像是一项正在进行的工作,所以我要为将来的修改做好准备,创建两个可以稍后查阅的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
https://stackoverflow.com/questions/51565154
复制相似问题