【问题标题】:Python - parse, split and separate text into individual rowsPython - 将文本解析、拆分和分离成单独的行
【发布时间】:2019-08-06 21:41:56
【问题描述】:

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

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

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

我希望它看起来像这样:

ID |报告文本

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

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

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

ID |报告文本

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

【问题讨论】:

    标签: python csv parsing text split


    【解决方案1】:

    您可以将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.
    

    独库:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2019-07-11
      • 2018-11-24
      相关资源
      最近更新 更多