如何创建已超过限速的车主的新文本文件?

2024-09-28 05:26:46 发布

您现在位置:Python中文网/ 问答频道 /正文

Suh基本上有一个文本文件,里面有许多超速的违法者的地址、姓名和车辆登记信息。文本文件中的一条记录如下所示:

reg: TW04AND
name: Karlie Kloss
address: 1 Hotstuff Road, BD7 4BT, Bradford

然后是另一个文件,包含另一组结果,地址刚刚超过标准车牌登记的速度限制,条目如下所示:

114mph = WE64NGL

或者

78mph = XD01SMH

这样它就可以比较这两个文件,并产生另一个文件与再犯罪者。我知道如何创建一个新的文本文件,但它的比较和输出,我挣扎和我感谢如果有人能帮助我。提前感谢:)


Tags: 文件name信息address地址记录reg姓名
2条回答

学习如何用python读取文本文件是一个快速的搜索过程,但是无论如何,这里有一个适合您的文件结构的代码示例。你知道吗

遵循这个结构

reg: TW04AND
name: Karlie Kloss
address: 1 Hotstuff Road, BD7 4BT, Bradford

下面的代码将读取文本文件并为每个数据集创建一个包含字典的列表。你知道吗

offender_lst = [] # List to contain each dictionary
d = {} # Create initial reference for d ( in case the first line doesn't start with reg )

with open("offender_lst.txt") as f: # Open the text file
    for line in f: # Iterate through the file
        line = line.strip() # remove \n character from line

        if not line: # If line is empty continue
            continue

        # If the line starts with reg overwrite d with empty dict
        if line.startswith("reg"):
            d = {}

        # Partition the line
        head, sep, tail = line.partition(": ")
        # Add them to dict
        d[head] = tail

        # If the line starts with address (last line of set)
        # Append the dict to list
        if line.startswith("address"):
            offender_lst.append(d)

print(offender_lst)

看起来您可以将两个文件中的所有数据读入字典,并使用图版作为密钥存储罪犯信息。然后按车牌搜索,根据需要检查之前是否发生过超速事故。你知道吗

offenders = {}

def normalize_line(line, delim):
    normalized = " ".join(line.split())
    first, second= normalized.split(delim)
    return first.strip(), second.strip()

with open("offender_info.txt") as f:
    line = f.readline()
    while line:
        if line.startswith("reg"):
            # parse plate line
            _, plate = normalize_line(line, ':')
            # parse name line
            _, name = normalize_line(f.readline(), ':')
            # parse address line
            _, address = normalize_line(f.readline(), ':')

            # save offender
            offenders[plate] = {
                'name': name,
                'address': address,
                'speeding_incidents': [],
            }

        line = f.readline()

with open("speeding_incidents.txt") as f:
    for line in f:
        speed, plate = normalize_line(line, '=')
        offenders[plate]['speeding_incidents'].append(speed)

print(offenders)

相关问题 更多 >

    热门问题