在每行后面加逗号和lab

2024-06-28 19:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python编写一个脚本来编写新行,然后用逗号和字符串标签附加该行。这是一段代码。你知道吗

new = open(newpath + "/" + "train" + ".txt", 'w')

for idx, tr in enumerate(train_data):
    new.write(train_data[idx] + ' , '  + str(index)

输出如下

Recommendations, thoughts, tips and tricks, or peanuts on moving from wordpress to django
 , 1Wordpress [caption] processing
 , 1Wordpress: query all images in a posts media library

逗号和标签会附加到行上,但会将其移到下一行。你知道吗

我需要它如下:

Recommendations, thoughts, tips and tricks, or peanuts on moving from wordpress to django , 1
Wordpress [caption] processing , 1
Wordpress: query all images in a posts media library , 1

Tags: orandinnewdataontrain标签
1条回答
网友
1楼 · 发布于 2024-06-28 19:22:36

根据您提供的内容,您的列车数据包含'\n'字符。因此,我建议您使用str.strip删除任何尾随空格和新行字符。你知道吗

for idx, tr in enumerate(train_data):
    new.write(train_data[idx].strip() + ' , '  + str(index))

我不知道index是从哪里来的,所以我把它放在里面了。你也不必索引你的数据,因为你可以迭代它。你知道吗

for tr in train_data:
    new.write(tr.strip() + ' , '  + str(index))

相关问题 更多 >