【问题标题】:Parsing text based on whitespace using Python使用 Python 基于空格解析文本
【发布时间】:2018-10-05 02:32:08
【问题描述】:
            No time. Not today.
                (slides in last bullets)
            Ten, eleven, twelve... or bust.
                (chambers a shell into each
                 gun, looks up)
            Right here!

The cab SCREECHES to a stop on the shoulder of the highest
FREEWAY in a massive INTERCHANGE of freeways. Dopinder halts
the meter and hands Deadpool his CARD.

我的目标是解析上述文本,使对话与描述分开。我的文件中有多个这样的实例。输出应该是两个单独的字符串xy,其中:

x = "No time. Not Today...Right Here!"

y = "The cab SCREECHES...his CARD"

如何使用正则表达式匹配来实现这一点?或者有没有更好的方法来解决这个问题?我正在使用 python。

【问题讨论】:

    标签: python regex parsing split


    【解决方案1】:

    好像连续两个换行符是文本各节的分隔符,所以可以拆分:

    x, y = s.split('\n\n')
    

    您还可以通过检查变量的第一个字符来确定变量是否为对话框。如果它们是空格(即有缩进),那么它就是一个对话框:

    x.startswith('            ') # True if dialog, False otherwise
    

    如果您需要删除每个字符串前后的多余空格,请使用strip

    x, y = [x.strip() for x in s.split('\n\n')]
    

    这样做您将无法检查某些内容是否为对话框,因此请务必在删除空格之前对其进行检查。

    【讨论】:

    • 一旦我这样做了,有没有办法让我检查哪个是对话,哪个是基于缩进的叙述?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多