Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—将文本解析、拆分和分离为单独的行_Python_Csv_Parsing_Text_Split - Fatal编程技术网

Python—将文本解析、拆分和分离为单独的行

Python—将文本解析、拆分和分离为单独的行,python,csv,parsing,text,split,Python,Csv,Parsing,Text,Split,我有一个文本文件,其中包含要导入Access数据库的数据。文本文件中包含了我想放在一行中的几个段落。我用“@@@1”分隔了每一行的位置 下面是我的一个例子: @@@我想去上学,因为它太有趣了。废话废话。我今天玩得很开心我无缘无故地很高兴。废话废话。我今天玩得很开心 我希望这样显示: ID |报告文本 我想去上学,因为它很有趣。废话 胡说八道。我今天玩得很开心 2 |我无缘无故如此高兴。废话废话。我是 今天玩得很开心 但是,我知道我的代码很接近,但我得到了以下信息: ID |报告文本 我想去上学,

我有一个文本文件,其中包含要导入Access数据库的数据。文本文件中包含了我想放在一行中的几个段落。我用“@@@1”分隔了每一行的位置

下面是我的一个例子:

@@@我想去上学,因为它太有趣了。废话废话。我今天玩得很开心我无缘无故地很高兴。废话废话。我今天玩得很开心

我希望这样显示:

ID |报告文本

我想去上学,因为它很有趣。废话 胡说八道。我今天玩得很开心

2 |我无缘无故如此高兴。废话废话。我是 今天玩得很开心

但是,我知道我的代码很接近,但我得到了以下信息:

ID |报告文本

我想去上学,因为它很有趣。废话 胡说八道

我今天玩得很开心

3 |我无缘无故如此高兴。废话废话。我是 有这么多

我今天玩得很开心

我尝试使用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

您可以将
split(@@')
枚举(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.
Doku: