python- txt组合线以字母开头

发布于 2025-02-14 01:03:40 字数 622 浏览 0 评论 0原文

我有一个庞大的TXT文件,其中包含行数据。 有些是空白的,有些以数字(日期)和文本开头。该结构重复出现,如下面的示例所示。

我想创建一个新文件,其中所有行从日期开始,然后是由逗号分隔的文本行。

我想我需要两个变量来存储以数字和文本开头的行,然后组合文本,直到找到下一个数字为止,但是我不知道该如何。

任何帮助都很棒!谢谢!

例子:

Input

22-05-16 20:35:20
ABC:D
UP:84.4,DN:84.3,Q=93
F: 35.7967
V: 0.50642
P:       0x1
Lev: 1483.64

22-05-16 21:30:00
ABC:D
UP:84.4,DN:84.3,Q=93
F: 35.7967 
V: 0.50642
P:       0x1
Lev: 1483.64

Output:

22-05-16 20:35:20, ABC:D, UP:84.4,DN:84.3,Q=93,F: 35.7967,V: 0.50642,P:       0x1,Lev: 1483.64 
22-05-16 21:30:00, ABC:D, UP:84.4,DN:84.3,Q=93,F: 35.7967,V: 0.50642,P:       0x1,Lev: 1483.64 

I have a huge txt file with data by lines.
There are some that are blank, some that start with a number (date) and by text. The structure repeats itself as shows in the example below.

I want to create a new file where all the lines start with the date, followed by the text lines separated by a comma.

I suppose I need two variables to store the lines that start with number and text and combine the text ones until the next number is found, but I don´t know how to to that.

Any help would be great! Thanks!

Example:

Input

22-05-16 20:35:20
ABC:D
UP:84.4,DN:84.3,Q=93
F: 35.7967
V: 0.50642
P:       0x1
Lev: 1483.64

22-05-16 21:30:00
ABC:D
UP:84.4,DN:84.3,Q=93
F: 35.7967 
V: 0.50642
P:       0x1
Lev: 1483.64

Output:

22-05-16 20:35:20, ABC:D, UP:84.4,DN:84.3,Q=93,F: 35.7967,V: 0.50642,P:       0x1,Lev: 1483.64 
22-05-16 21:30:00, ABC:D, UP:84.4,DN:84.3,Q=93,F: 35.7967,V: 0.50642,P:       0x1,Lev: 1483.64 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

壹場煙雨 2025-02-21 01:03:40

您可以累积所有行,直到看到空白行并遇到空白后写入累积的字符串 -

with open('infile.txt', 'r') as to_read, open('outfile.txt', 'w') as to_write:
    acc_str = ''
    for line in to_read:
        if line.strip() == '':
            to_write.write(acc_str + '\n')
            acc_str = ''
        acc_str += line.strip() + ' '
    else:
        to_write.write(acc_str)

输出

 22-05-16 20:35:20 ABC:D UP:84.4,DN:84.3,Q=93 F: 35.7967 V: 0.50642 P:       0x1 Lev: 1483.64 
 22-05-16 21:30:00 ABC:D UP:84.4,DN:84.3,Q=93 F: 35.7967 V: 0.50642 P:       0x1 Lev: 1483.64 

You could accumulate all lines until you see a blank line and write the accumulated string once you encounter a blank -

with open('infile.txt', 'r') as to_read, open('outfile.txt', 'w') as to_write:
    acc_str = ''
    for line in to_read:
        if line.strip() == '':
            to_write.write(acc_str + '\n')
            acc_str = ''
        acc_str += line.strip() + ' '
    else:
        to_write.write(acc_str)

Output

 22-05-16 20:35:20 ABC:D UP:84.4,DN:84.3,Q=93 F: 35.7967 V: 0.50642 P:       0x1 Lev: 1483.64 
 22-05-16 21:30:00 ABC:D UP:84.4,DN:84.3,Q=93 F: 35.7967 V: 0.50642 P:       0x1 Lev: 1483.64 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文