如何分离从文本文件读取的数据行?客户的订单



我在一个文本文件中有这些数据。(没有我为清晰起见添加的间距(

我正在使用Python3:

orders = open('orders.txt', 'r')
lines = orders.readlines()

我需要循环遍历包含所有数据行的行变量,并按照我的间距分隔CO行。CO是客户,每个CO下面的行是客户下的订单。

如果你看一下CO字符串的索引[7-9],CO行告诉我们有多少行订单。我在下面举例说明。

CO77812002D10212020       <---(002)
125^LO917^11212020.      <----line 1
235^IL993^11252020       <----line 2 
CO77812002S10212020
125^LO917^11212020
235^IL993^11252020
CO95307005D06092019    <---(005)
194^AF977^06292019    <---line 1 
72^L223^07142019       <---line 2
370^IL993^08022019    <---line 3
258^Y337^07072019     <---line 4
253^O261^06182019     <---line 5
CO30950003D06012019
139^LM485^06272019
113^N669^06192019
249^P530^07112019
CO37501001D05252020
479^IL993^06162020

我想了一种蛮力的方法来做这件事,但它对更大的数据集不起作用。

如有任何帮助,我们将不胜感激!

您可以使用fileinput(源(来"同时">读取并修改您的文件。事实上,通过第二个备份文件实现了就地功能,该功能提供在解析文件时修改文件。具体而言,如下所述:

可选的就地筛选:如果将关键字参数inplace=True传递给fileinput.input((或fileinput构造函数,则文件被移动到备份文件,标准输出默认定向到输入文件(…(,扩展名为".bak",并在关闭输出文件时删除。

因此,您可以按照指定的方式格式化文件:

import fileinput
with fileinput.input(files = ['orders.txt'], inplace=True) as orders_file:
for line in orders_file:
if line[:2] == 'CO':    # Detect customer line
orders_counter = 0
num_of_orders = int(line[7:10])    # Extract number of orders
else:
orders_counter += 1
# If last order for specific customer has been reached
# append a 'n' character to format it as desired
if orders_counter == num_of_orders:
line += 'n'
# Since standard output is redirected to the file, print writes in the file
print(line, end='')

注意应该按照您指定的方式对带有订单的文件进行格式化

CO...
(order_1)
(order_2)
...
(order_i)
CO...
(order_1)
...

这是我希望完成的!

tot_customers = []
with open("orders.txt", "r") as a_file:
customer = []
for line in a_file:
stripped_line = line.strip()
if stripped_line[:2] == "CO":
customer.append(stripped_line)
print("customers: ", customer)
orders_counter = 0
num_of_orders = int(stripped_line[7:10])
else:
customer.append(stripped_line)
orders_counter +=1
if orders_counter == num_of_orders:
tot_customers.append(customer)
customer = []
orders_counter = 0

最新更新