我有一个文本文件,其中包含要导入Access数据库的数据。这个文本文件包含了几个段落,我想把它们放在一行中。我已经用“@@@
下面是我的一个例子:
@@我想去学校,因为那里很有趣。等等等等等等。我今天玩得很开心我无缘无故地高兴。等等等等等等。我今天玩得很开心
我希望这样:
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.
但是,我知道我的代码已经很接近了,但是我明白了:
ID | Reporttext
1 | I would like to go to school because it's so much fun. Blah Blah Blah Blah.
2 | I am having so much fun today.
3 | I am so happy for no reason. Blah Blah Blah Blah Blah. I am having so much
4 | I am having so much fun today.
我尝试使用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("@@@")
和enumerate(iterable,start_index)
与生成器表达式结合使用:输出:
独行:
相关问题 更多 >
编程相关推荐