[英]How to compare two files data to check for a match then output to a new file in python 3.4
I am making a system that needs to search two .txt files for matching information (registration plates), if the system finds a match then it needs to output the lines from both files to a new file. 我正在制作一个系统,该系统需要搜索两个.txt文件以获取匹配信息(注册牌),如果系统找到匹配项,则需要将两个文件中的行输出到一个新文件中。 The files: one contains data on speeding vehicles (regplate:speed data), the other contains vehicles registrations and owners details ( regplate:owners information).
这些文件:一个包含有关超速车辆的数据(regplate:速度数据),另一个包含车辆注册和车主详细信息(regplate:车主信息)。 I have currently created a system that will find the owners information using an input and a line.startswith () command but I need the system to check through every plate in the speeding file and check if the same plate is in the owners information file, if it is then both pieces of data should be outputted to a new file.
我目前已经创建了一个系统,该系统将使用输入和line.startswith()命令查找车主信息,但是我需要该系统检查超速文件中的每个车牌,并检查车主信息文件中是否有相同的车牌,如果是,则应将两条数据都输出到新文件。 Is there a way I can do this with the .startswith()?.
我可以用.startswith()方法吗? If not what other ways do you suggest.
如果没有,您建议采取什么其他方式。 In both files every line starts with a different registration plate.
在两个文件中,每一行都以不同的车牌开头。
My current code: 我当前的代码:
import re
with open("Speeding.txt", "r") as f:
list1 = []
for line in f:
list1.append(line)
listnew = str(list1)
listnew.replace("\n", "")
new=open('SpeedersDetails.txt', 'a')
platecheck=input('Input plate: ')
with open('Plates.txt', 'r') as platefilereopen:
for line in platefilereopen:
if line.startswith(platecheck):
new.write(line)
new.write('\n')
new.close()
f.close()
My files: Ownersdetails , Speeding 我的文件: 所有者详细信息 , 超速驾驶
You could go through one file and create a dictionary defaultdict(list)
with registration plates as keys, and "speed data" appended to the list value. 您可以浏览一个文件,并创建一个字典
defaultdict(list)
其中的登记牌为键,并将“速度数据”附加到列表值中。 Then go through the other file and for each registration plate in the dictionary, append "owners information". 然后浏览另一个文件,并为词典中的每个车牌添加“所有者信息”。 Now you can run through the dictionary items and output each entry with a list of length two.
现在,您可以遍历字典项,并输出每个条目并列出长度为2的列表。
for reg_plate, info_list in reg_plate_dict.items():
if len(info_list) == 2:
speed_data, owner_info = value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.