[英]compare two files of different formats in python
比较 Python 中不同格式的两个不同文件的最佳方法是什么。
File1: strings
Type=Test Id=00001 Time=7:41pm Desc=Test Qt=1
Type=Update Id=34234 Time=7:42pm Desc=ABC Qt=1
Type=New Id=12345 Time=7:42pm Desc=ABC Qt=1
File2: json
{"Type":"New","Id":"12345","Time":"17:42:43","Title":"ABC","Quantity":1}
每个文件有 20,000 多行并且不会逐行匹配,因此文件 1 中的第 100 行与文件 2 中的第 100 行不同。
目前,我解析出文件 1 中的 ID,并在整个文件 2 中搜索该 ID,然后在找到它时中断。 但是,当我深入研究文件 2 时,解析每个条目需要更长的时间。
我有理由相信,如果我在文件 2 中找到 Id=12345,那么 Id=12346 将在该文件之后。 所以我想文件 1 的第二个条目应该从它找到的第一个条目开始搜索文件 2。
def parse_file1(self, file1, file2):
for i, log_line in enumerate(open(file1, "r").readlines()):
mydict = dict(item.split("=") for item in line.split(" "))
if "New" in mydict['Type']:
id = mydict['Id']
result = self.parse_file2(id, file2)
def parse_file2(self, id, file2):
result = 0
for i, line in enumerate(open(file2, "r").readlines()):
fileOneDict = json.loads(line)
if str(fileOneDict['Type']) == "New":
if id == str(fileOneDict['Id']):
result += 1
break
return result
从您显示的代码中可以看出,您只对两个文件中分别指定Type=New
和"Type": "New"
的条目感兴趣。 如果是这样,那么我将一次一行读取file2
指定的文件(无需将整个文件读入内存),对于那些键 'Type' 值为New
的字典实例,我将收集这些字典值在另一个字典file2_dict
中,其键是转换为字符串的字典的“Id”值。 这允许我找到给定 id 的字典作为 O(1) 操作。 然后我会处理file1
指定的文件的每一行,如果它的类型是 'New' 我会使用它的 'Id' 值在file2_dict
中查找相应的file2
字典。 如果它存在,那么我可以对我希望的两个字典条目进行任何进一步的比较:
import json
class Comparer:
def __init__(self, file1, file2):
self.file1, self.file2 = file1, file2
def parse_files(self):
file2_dict = {}
with open(self.file2, 'r') as f:
for line in f:
d = json.loads(line)
if d['Type'] == 'New':
str_id = str(d['Id'])
# store this in file2_dict keyed by str_id
file2_dict[str_id] = d
with open(self.file1, 'r') as f:
for line in f:
d1 = dict(item.split("=") for item in line.split())
#if 'New' in d['type']:
if d1['Type'] == 'New':
d2 = file2_dict.get(d1['Id'])
if d2:
self.compare(d1, d2)
def compare(self, d1, d2):
""" Compare two dictionary entries from file1 and file2 """
pass
Comparer('test1.txt', 'test2.txt').parse_files()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.