【问题标题】:Partitioning multiline string in python在python中对多行字符串进行分区
【发布时间】:2015-01-06 14:21:50
【问题描述】:

我正在使用 python 脚本运行一个 unix 命令,我将它的输出(多行)存储在一个字符串变量中。 现在我必须使用该多行字符串创建 3 个文件,方法是将其分成三个部分(由模式 End---End 分隔)。

这是我的输出变量包含的内容

Output = """Text for file_A
something related to file_A
End---End
Text for file_B
something related to file_B
End---End
Text for file_C
something related to file_C
End---End"""

现在我想要三个文件 file_A、file_B 和 file_C 用于输出的这个值:-

file_A

的内容
Text for file_A
something related to file_A

file_B

的内容
Text for file_B
something related to file_B

file_C

的内容
Text for file_C
something related to file_C

另外,如果 Output 没有对应文件的任何文本,那么我不希望创建该文件。

例如

Output = """End---End
Text for file_B
something related to file_B
End---End
Text for file_C
something related to file_C
End---End"""

现在我只想创建 file_B 和 file_C,因为 file_A 没有文本

file_B

的内容
Text for file_B
something related to file_B

file_C

的内容
Text for file_C
something related to file_C

如何在 python 中实现这一点?是否有任何模块可以使用某些分隔符对多行字符串进行分区?

谢谢:)

【问题讨论】:

    标签: python file multilinestring


    【解决方案1】:

    您可以使用split() 方法:

    >>> pprint(Output.split('End---End'))
    ['Text for file_A\nsomething related to file_A\n',
     '\nText for file_B\nsomething related to file_B\n',
     '\nText for file_C\nsomething related to file_C\n',
     '']
    

    由于末尾有'End---End',所以最后一次拆分返回'',所以可以指定拆分次数:

    >>> pprint(Output.split('End---End',2))
    ['Text for file_A\nsomething related to file_A\n',
     '\nText for file_B\nsomething related to file_B\n',
     '\nText for file_C\nsomething related to file_C\nEnd---End']
    

    【讨论】:

    • 赞成这个答案,因为这个问题似乎是一个家庭作业问题,所以除了提示之外,还会犹豫。
    • 谢谢!呃!!我真的应该停止来这个论坛高 :D 这证明了我的名字 8-)
    【解决方案2】:
    Output = """Text for file_A
    something related to file_A
    End---End
    Text for file_B
    something related to file_B
    End---End
    Text for file_C
    something related to file_C
    End---End"""
    
    ofiles = ('file_A', 'file_B', 'file_C')
    
    def write_files(files, output):
        for f, contents in zip(files, output.split('End---End')):
            if contents:
                with open(f,'w') as fh:
                    fh.write(contents)
    
    write_files(ofiles, Output)
    

    【讨论】:

      猜你喜欢
      • 2015-05-03
      • 2012-03-11
      • 2013-08-29
      • 2014-03-28
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多