如何用字符串列表编辑.txt文件

2024-06-16 14:45:42 发布

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

我有一个包含字符串列表的.txt文件,每行一个列表:

['Animals', 'Endoplasmic Reticulum', 'Humans']

我想编辑每一行,像这样:

training/197 animals endoplasmic reticulum humans

其中“training”是我之前在函数中分配的变量(即,这将被忽略),“197”是该行的索引,下面的单词是该行中列表的所有元素。你知道吗

我不太清楚如何抓取和“连接”所有这些(超过打开文件和为每行设置for循环的点),因此任何帮助都将不胜感激。你知道吗


Tags: 文件函数字符串txt编辑列表traininghumans
2条回答

试试这个:

对于输入文件输入文件

['AAA', 'BBB CCC', 'DDD']
['EEE', 'FFF', 'GGG']

那个输出文件.txt是:

training/0 AAA BBB CCC DDD
training/1 EEE FFF GGG

代码:

with open('input.txt') as input_file, open('outfile.txt','w') as out_file:
    row_index = 0
    any_string = 'training'
    for line in input_file.readlines():
        line_list = eval(line)
        final_row_string = '{}/{} {}\n'.format(any_string, row_index, str(' '.join(line_list)))
        out_file.write(final_row_string)
        row_index += 1

正如你所说:

"training" is a variable I have previously assigned inside a function (i.e. this is to be ignored),

所以我给你的解决方案是:

I'm not quite sure how to grab and "join" all of this (past the point of opening the file and having a for loop for each line):

您可以尝试:

这只是一个示例,您可以根据需要进行修改:

import ast

with open('file.txt','r') as f:
    for line in f:
        print(*ast.literal_eval(line))

将为您提供输出:

Animals Endoplasmic Reticulum Humans

你可以检查它的类型

print(type(ast.literal_eval(line)))

即:

<class 'list'>

所以你可以根据你的要求对这个做所有的列表操作。你知道吗

相关问题 更多 >