【问题标题】:How do i create a new text file of vehicle owners who have already exceeded the speed limit?如何为已经超速的车主创建一个新的文本文件?
【发布时间】:2016-02-21 13:34:39
【问题描述】:

Suh 基本上有一个文本文件,其中包含许多超出限速的罪犯的地址、姓名和车辆登记信息。文本文件中的一条记录如下所示:

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

然后他们是另一个文件,其中包含另一组结果,地址最近刚刚超过标准车牌注册的速度限制,条目如下所示:

114mph = WE64NGL

78mph = XD01SMH

这样它将比较两个文档并生成另一个文档与重新犯罪者。我知道如何创建一个新的文本文件,但是如果有人可以帮助我,我会很努力地比较和输出它,我很感激。在此先感谢:)

【问题讨论】:

  • 所有你需要做的就是读取两个文本文件,将它们存储在一个列表中,然后遍历它们以找到匹配项。

标签: python python-3.x compare output


【解决方案1】:

学习如何使用 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)

【讨论】:

    【解决方案2】:

    看起来您可以将两个文件中的所有数据读取到字典中,并使用车牌作为键来存储罪犯信息。然后只需按车牌搜索,根据需要检查之前的超速事故。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多