首页 > 解决方案 > Python - 将文本解析、拆分和分离成单独的行

问题描述

我有一个文本文件,其中包含要导入 Access 数据库的数据。文本文件包含几段我想进入一行。我已经用“@@@”分隔了我想要的每一行

所以这是我所拥有的一个例子:

@@@我想去上学,因为它很有趣。呜呜呜呜呜呜。我今天玩得很开心。@@@我无缘无故的高兴。呸呸呸呸呸。我今天玩得很开心。

我希望它看起来像这样:

身份证 | 报告文本

1 | 我想去上学,因为它很有趣。呜呜呜呜呜呜。我今天玩得很开心。

2 | 我无缘无故地高兴。呸呸呸呸呸。我今天玩得很开心。

但是,我知道我的代码很接近,但我得到了这个:

身份证 | 报告文本

1 | 我想去上学,因为它很有趣。呜呜呜呜呜呜。

2 | 我今天玩得很开心。

3 | 我无缘无故地高兴。呸呸呸呸呸。我有这么多

4 | 我今天玩得很开心。

我尝试了一个 IF 语句,只在行中有“@@@”时添加 ID,但我无法让它工作。如果我这样做了,我认为它应该可以工作。我有 ID 和 reporttext 使用分号作为分隔符。

这是我的代码:

import csv

with open("by2.txt") as txt, open('theoutput2.txt', 'a') as csvfile:
    writer = csv.writer(csvfile, delimiter=';')
    writer.writerow(('ID', 'Reporttext'))
    Id = 1
    for line in txt:
        words = line.strip().split("@@@")
        for word in words:
            writer.writerow((id, word.strip()))
            id += 1

标签: pythoncsvparsingtextsplit

解决方案


您可以组合split("@@@")enumerate(iterable,start_index)结合生成器表达式:

t = """@@@ I would like to go to school because it's so much fun. Blah Blah Blah Blah. I am having so much fun today. @@@ I am so happy for no reason. Blah Blah Blah Blah Blah. I am having so much fun today."""

# split and enumerate(starting at 1)
# the if conditional inside the generator expression eleminates empty lines  
data = list(enumerate( (x.strip() for x in t.split("@@@") if x.strip()), 1))

print(data)
print("")

import csv
with open("t.txt", "w", newline = "") as csvfile:
    writer = csv.writer(csvfile, delimiter=';')
    writer.writerow(('ID', 'Reporttext'))
    writer.writerows(data)

print( open("t.txt").read())

输出:

# data
[(1, "I would like to go to school because it's so much fun. Blah Blah Blah Blah. I am having so much fun today."), 
 (2, 'I am so happy for no reason. Blah Blah Blah Blah Blah. I am having so much fun today.')]


# file
ID;Reporttext
1;I would like to go to school because it's so much fun. Blah Blah Blah Blah. I am having so much fun today.
2;I am so happy for no reason. Blah Blah Blah Blah Blah. I am having so much fun today.

独库:


推荐阅读