Python 使用来自另一个文件的输入在文件中搜索文本 [英] Python search a file for text using input from another file
本文介绍了Python 使用来自另一个文件的输入在文件中搜索文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Python 和编程的新手.我需要一些关于 python 脚本的帮助.有两个文件,每个文件都包含电子邮件地址(超过 5000 行).输入文件包含我想在数据文件中搜索的电子邮件地址(也包含电子邮件地址).然后我想将输出打印到文件或在控制台上显示.我搜索脚本并能够修改,但我没有得到想要的结果.你能帮我吗?
I'm new to python and programming. I need some help with a python script. There are two files each containing email addresses (more than 5000 lines). Input file contains email addresses that I want to search in the data file(also contains email addresses). Then I want to print the output to a file or display on the console. I search for scripts and was able to modify but I'm not getting the desired results. Can you please help me?
dfile1 (50K lines)
yyy@aaa.com
xxx@aaa.com
zzz@aaa.com
ifile1 (10K lines)
ccc@aaa.com
vvv@aaa.com
xxx@aaa.com
zzz@aaa.com
Output file
xxx@aaa.com
zzz@aaa.com
datafile = 'C:\\Python27\\scripts\\dfile1.txt'
inputfile = 'C:\\Python27\\scripts\\ifile1.txt'
with open(inputfile, 'r') as f:
names = f.readlines()
outputlist = []
with open(datafile, 'r') as fd:
for line in fd:
name = fd.readline()
if name[1:-1] in names:
outputlist.append(line)
else:
print "Nothing found"
print outputlist
新代码
with open(inputfile, 'r') as f:
names = f.readlines()
outputlist = []
with open(datafile, 'r') as f:
for line in f:
name = f.readlines()
if name in names:
outputlist.append(line)
else:
print "Nothing found"
print outputlist
推荐答案
我会这样做:
names=[]
outputList=[]
with open(inputfile) as f:
for line in f:
names.append(line.rstrip("\n")
myEmails=set(names)
with open(outputfile) as fd, open("emails.txt", "w") as output:
for line in fd:
for name in names:
c=line.rstrip("\n")
if name in myEmails:
print name #for console
output.write(name) #for writing to file
这篇关于Python 使用来自另一个文件的输入在文件中搜索文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文