繁体   English   中英

用特定字符替换行

[英]Replace lines with a specific character

输入:

ch1\tAa,Ab,Ac,;Ba,Bb,Bc,;\n
ch2\tCa,Cb,Cc,;Da,Db,Dc,;Ea,Eb,Ec,;\n

预期 output:

ch1\tAa,Ab,Ac,\n
''\tBa,Bb,Bc,\n
ch2\tCa,Cb,Cc,\n
''\tDa,Db,Dc,\n
''\tEa,Eb,Ec,\n

Output:

''\tch1\tAa,Ab,Ac,\n
Ba,Bb,Bc,\n
''\tch2\tCa,Cb,Cc,\n
Da,Db,Dc,\n
Ea,Eb,Ec,\n

代码:

with open(input, 'r') as fr, open(output, 'w') as fw:

    new_file_content = ''
    for line in fr:
        stripped_line = line.strip()
        new_line = '' + '\t' + stripped_line.replace(';', '\n')
        new_file_content += new_line + '\n'

    fw.write(new_file_content)
  1. 我想根据';'写其他行在一行中。
  2. 我想使用 '' + \t 来表示由 ';' 分隔的行。 对不起,你有什么建议给我吗?

尝试以下操作:

with open('input.txt', 'r') as f, open('output.txt', 'w') as g:
    for line in f:
        g.write(line.rstrip(';\n').replace(';', '\n\t'))
        g.write('\n')

(但是请注意,从技术上讲, rstrip(';\n')不会删除最右边的substring ';\n' 。它只是从右侧删除字符';''\n' 。您可能想使用而是删除后缀,以更安全(python removesuffix )。)

Output ( output.txt ; 空白是\t的)

ch1 Aa,Ab,Ac,
    Ba,Bb,Bc,
ch2 Ca,Cb,Cc,
    Da,Db,Dc,
    Ea,Eb,Ec,

我对你所说的你想要的以及你期望的 output 是什么感到困惑,但这应该是 output 你期望的 output 是什么。 我怀疑这是最好的方法,而且很混乱,但它应该有效。 我很困惑'\n'与'\\n'的含义,但你应该能够改变它。 如果这不是您想要的,对不起,请告诉我您想要什么,我会尝试修复代码。 另外,我不相信这是可扩展的。 在 for 循环中,我使用“-2”等,所以我认为它不适用于所有输入,但可以更改。 我希望这个对你有用:)

file:str=".\\file_1.txt"
new_file:str=".\\new_file_1.txt"

with open(file,'r') as fr,open(new_file,'w') as fw:
    new_file_content=''

    for line in fr:
        stripped_line=line.strip()
        new_line=''

        split_line:str=stripped_line.split(';')

        for a in range(len(split_line)-1):
            new_line=split_line[a]+"\\n"

            if a<len(split_line)-2:
                new_line+="\n''\\t"

            new_file_content+=new_line

        new_file_content+='\n'

    fw.write(new_file_content)

    print(open(new_file,'r').read())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM