【问题标题】:Read more than one line of a file读取多行文件
【发布时间】:2012-11-03 03:37:12
【问题描述】:

我正在开发一个 python 应用程序来为脚本(ish)视觉小说框架创建一个界面。现在,我能够读取文件,创建 标签 或函数,但是当我读取它们时,它只读取一行。有点像这样:

>>> from freddie import Freddie
>>> check = Freddie()
>>> check.read_script('script')
>>> check.read_label('start')
'label start:\n' # Only reads the first line and the whitespace

而整个标签是:

label start:

    test "Lorem ipsum"

    test "Sir amet"

return

我的功能是:

def read_label(self, label):
    search_label = re.search("label %s(.*)\s" % label, self.scripts.read(), re.MULTILINE)
    return search_label.group()

有没有办法让正则表达式读取整个标签和空格?

感谢您的宝贵时间。

【问题讨论】:

  • 我认为stackoverflow.com/questions/587345/… 回答了您的大部分疑问。
  • 确保在您的正则表达式中使用原始字符串,否则字符类(如 \s)将不起作用。
  • @kaotik 您的链接完成了部分工作,但它仅读取第一行,我希望表达式在返回语句之前读取。也许有一种方法可以对其进行一些修改以使整个工作正常?

标签: python regex python-2.7


【解决方案1】:

正则表达式中的. 通常匹配任何字符除了“\n”,因此正则表达式只匹配第一行(\s 匹配末尾的“\n”那行)。

如果您希望. 匹配任何字符包括“\n”,请使用DOTALL 标志。

【讨论】:

    猜你喜欢
    • 2011-12-26
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2014-12-10
    • 2016-04-28
    • 1970-01-01
    相关资源
    最近更新 更多