所以我有这个文本文件,我正在处理,我想用它的信息为我的停车系统

2024-05-12 22:14:01 发布

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

我的文本文件中的一行:

RCF585 medium Joseph -you entered the parking lot at 3:30 and left at 4:30- 

我想做的是通过车牌号识别汽车,然后知道它是“中等”(大小),因此它的总成本是(停车成本*1.25(税)),同时小的总成本是(停车成本*1.00)大的总成本是(停车成本*1.50)

停车成本(每半小时20美元)当然取决于汽车停放的时间,因此我的第二个问题是如何通过读取相关汽车的线路来读取和识别汽车停放的时间。以下是我迄今为止成功撰写的内容:

f=open(file, "r")

which_car= input("Please write your license number: ")

for line in f:

if line.startswith(which_car):        #identifying which car we want to deal with

Tags: theyouwhichline时间car汽车at
2条回答

我会使用Regex查找文本中的时间

import re

regex = re.compile(r'(\d{1,2}:\d\d)')
times = regex.findall(line)

并使用datetimedateutil.relativedelta查找停车时间

from datetime import datetime
from dateutil.relativedelta import relativedelta

parking_time = relativedelta(datetime.strptime(times[0] , '%H:%M'), datetime.strptime(times[1] , '%H:%M'))
minutes = abs((parking_time.hours * 60) + parking_time.minutes)

因此,所有这些加在一起将是:

import re
from datetime import datetime
from dateutil.relativedelta import relativedelta

which_car = input("Please write your license number: ")

with open(file, 'r') as f:
    
    for line in f:

        if line.startswith(which_car):

            size = line.split(' ')[1]

            regex = re.compile(r'(\d{1,2}:\d\d)')
            times = regex.findall(line)
             
            # Update - Ex. 3:27 -> 3:30, 3:35 -> 3:30
            for i in range(len(times)):

                minute = int(times[i].split(':')[1])

                if minute - ((minute // 15) * 15) < 7.5:
                    minute = (minute // 15) * 15
                else:
                    minute = (minute // 15 + 1) * 15

                times[i] = times[i].split(':')[0] + ':' + str(minute)

            parking_time = relativedelta(datetime.strptime(times[0] , '%H:%M'), datetime.strptime(times[1] , '%H:%M'))

            minutes = abs((parking_time.hours * 60) + parking_time.minutes)

            parking_cost = (minutes // 30) * 20
            total_cost = parking_cost   # Default size is small

            if size == 'big':
                total_cost = parking_cost * 1.5
            elif size == 'medium':
                total_cost = parking_cost * 1.25

我建议在处理文件时使用,因为您不必再担心手动关闭文件

可以使用^{}提取时间,使用^{}将提取的字符串转换为日期时间数据:

import re
from datetime import datetime

which_car = input("Please write your license number: ")
file = "text.txt"

with open(file, "r") as f:
    for line in f:
        if line.startswith(which_car):
            time1, time2 = re.findall("\d+:\d+", line)

def string_to_time(string):
    return datetime.strptime(string , '%H:%M')

print(string_to_time(time2) - string_to_time(time1))

试运行:

Please write your license number: RCF585

输出:

1:00:00

说明:

模式\d+:\d+仅表示冒号两侧的数字,格式%H:%M表示冒号两侧的小时值和分钟值

注意:使用=运算符将open调用分配给变量是一种不好的做法。相反,使用^{}语句

相关问题 更多 >