我会建议你从不同的角度接近这一点。首先,沿选项卡分割每行,然后单独验证每个条目。这使您可以编译每个条目的正则表达式并编译更精确的错误消息。一个很好的方式做,这是元组拆包和分割方法:
from __future__ import print_function
with open("input.txt") as in_file, open("output.txt", 'w') as out_file:
next(in_file) # skips header
for line in in_file:
error_message = []
# remove line break character and split along the tabs
id_and_date, user_id, p1, p2, p3, p4, url = line.strip("\n").split("\t")
# split the first entry at the first :
split_id_date = id_and_date.split(":", 1)
if len(split_id_date) == 2:
order_id, date = split_id_date
elif len(split_id_date) == 1:
# assume this is the order id
# or do something
order_id, date = (split_id_date[0], "")
error_message.append("Invalid Date")
else:
# set default values if nothing is present
order_id, date = ("", "")
# validate order_id and date here using re.match
# add errors to error_message list:
# error_message.append("Invalid Date")
# calculate average price
# first, compile a list of the non-zero prices
nonzero_prices = [int(x) for x in (p1, p2, p3, p4) if int(x) > 0] # this can be done more efficient
# compute the average price
avg_price = sum(nonzero_prices)/len(nonzero_prices)
# validate url using re here
# handle errors as above
print("\t".join([order_id, date, user_id, str(avg_price), url, ", ".join(error_message)]), file=out_file)
我没有添加re
调用验证项,因为我不知道你期望中的条目,看看到底是什么。不过,我在re.match
或其他类似的电话会议中添加了一条评论。
我希望这会有所帮助。
我建议使用'csv'模块读取和写入文件。它可以为你处理很多特殊情况。还建议你[编辑]你的问题,并显示一个长输入文件的例子,其中包含所有特殊情况以及预期输出应该如何。 – martineau
我添加了输入和输出文件的图像来解释我想要做的更好。感谢您的建议。该帖子太令人困惑了 – ashu138
其实我的意思是让你从这两个文件中剪切出行并将它们粘贴到你的问题中(缩进4个空格)。这样,有人可以使用第一个能够运行你的代码,第二个来检查结果。 – martineau