gpt4 book ai didi

Python 使用来自另一个文件的输入在文件中搜索文本

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:17 24 4
gpt4 key购买 nike

我是 Python 和编程的新手。我需要一些关于 python 脚本的帮助。有两个文件,每个文件都包含电子邮件地址(超过 5000 行)。输入文件包含我要在数据文件中搜索的电子邮件地址(也包含电子邮件地址)。然后我想将输出打印到文件或显示在控制台上。我搜索脚本并能够修改,但我没有得到想要的结果。你能帮帮我吗?

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

最佳答案

也许我遗漏了什么,但为什么不使用一对呢?

#!/usr/local/cpython-3.3/bin/python

data_filename = 'dfile1.txt'
input_filename = 'ifile1.txt'

with open(input_filename, 'r') as input_file:
input_addresses = set(email_address.rstrip() for email_address in input_file.readlines())

with open(data_filename, 'r') as data_file:
data_addresses = set(email_address.rstrip() for email_address in data_file.readlines())

print(input_addresses.intersection(data_addresses))

关于Python 使用来自另一个文件的输入在文件中搜索文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19933813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com