我正在寻找一个程序,可以使用模块re从文件中挑选汽车信息。询问用户关于他想要查看的汽车的问题,并且如果输入不在文件中,我应该显示错误消息并且如果用户想要再次循环代码。我有困难要查找的文件中输入:这是迄今为止代码:如何使用模块re在文件中查找关键字
import re
import random
myList = ([])
car = input("What car do you want to view?");
myList.insert(1, car)
model = input("What car model is it of");
myList.insert(2, model)
fuelTy = input("What fuel type is it: diseal or petrol");
myList.insert(3, fuelTy)
engSize = input("What engine size is it : eg 2l");
myList.insert(4, engSize)
rnd = (int(random.randrange(50000000)) + 1)
with open("car.txt", "r") as carfile:
for line in carfile:
if all(myList.lower() in re.findall('\w+', line.lower()) for myList in carfile):
splitted_line = line.split(':')
print(splitted_line)
if not myList not in carfile:
print("We don't have the car available currently. Please contact the head office with the case number " + str(rnd))
Cho2 = input("Would you like to see anything yes or no").lower
if Cho2 == "yes":
print("OK")
elif Cho2 == "no":
print("End of program")
文本文件: 宝马:X6:3.4升:发动机尺寸4395cc:汽油:0-62mph 4.8 s:档位自动:5门:经济型29mpg:最高时速155 mph audi:Q7:3.0l:发动机尺寸2967cc:反应:0-62mph 6.5s:档位自动:5门:经济:48mpg:最高速度145英里/小时 本田:CRV:2.0l:发动机大小1997cc:汽油:10.0s:0-62mph:齿轮式手动:5门:经济30mpg:最高时速18英里每小时
你的文件看起来像一个“:”分隔的文件。试试'str.split(“:”)'来看看你是否可以得到一个好的列表,然后查找你想要的元素的索引。如果你有一个标题行,你可以使用'namedtuple'来存储每一行。否则,我建议你使用http://pythex.org并自己提出正则表达式作为练习。但是我怀疑你毕竟需要'重新'。 – Mai
但是代码不起作用,即使您输入BMW X6也只打印本田信息,所以我可以帮助解决。 –