【问题标题】:How to do universal newline detection on string objects in python?如何对python中的字符串对象进行通用换行检测?
【发布时间】:2014-08-21 14:05:56
【问题描述】:

我的目标是检测字符串对象使用的确切类型的换行符。

如果你open 一个文件,你可以让它在内部使用universal newline support,与'U''rU'。但是,假设您需要处理不是文件的字符串对象。 re 可以,但听起来有点矫枉过正。

是否可以确定字符串对象的换行符类型?

EOL 中的many kinds of representations 中,我对三个感兴趣:"\n" 你通常使用,"\r\n" 用于 Windows/DOS/CP/M/OS/2"\r" 用于旧版 Mac

【问题讨论】:

    标签: python string newline detection


    【解决方案1】:

    在写这个问题的时候,我找到了以前一直想不通的答案。

    内置函数str.splitlines(True) 允许您确定换行符。来自文档:

    例如,'ab c\n\nde fg\rkl\r\n'.splitlines()
    返回['ab c', '', 'de fg', 'kl'],

    同时与splitlines(True)进行相同的通话
    返回['ab c\n', '\n', 'de fg\r', 'kl\r\n']

    注意:这不是我想要的,因为换行符附加到块中,所以如果你知道更好的方法,请告诉!

    【讨论】:

    • 哇,我用Python很久了,从来不知道这个功能。 +1!
    • 所以您只想将字符串拆分为行或知道使用了什么换行符序列?如果是第二个,如果使用几个不同的序列会怎样,就像在你的样本中一样?
    • @AntonSavin 我想知道使用了什么换行符。如果有不同的序列,我对内置函数和模块中最接近此任务的任何内容感兴趣。
    • @naxa 那么你最终采用了什么解决方案?
    【解决方案2】:

    您不能检查未拆分字符串中是否存在可能的行尾吗?例如

    def find_line_ending(s):
        if '\r\n' in s:  # Check this one first
            return '\r\n'
        if '\r' in s:
            return '\r'
        if '\n' in s:
            return '\n'
        return None  # No line endings in string
    

    这至少意味着您知道如果同一字符串中出现多个类型会发生什么。

    【讨论】:

      【解决方案3】:

      这是一个简单的函数,它计算所有三种类型的换行符序列在整个字符串中的出现次数:

      def countNewlines(s):
          numRN = 0;
          numR = 0;
          numN = 0;
          prev = '';
          for c in s:
              if c == '\n':
                  if prev == '\r':
                      numRN += 1;
                  else:
                      numN += 1;
              elif prev == '\r':
                  numR += 1;
              prev = c;
          if prev == '\r':
              numR += 1;
          return (numRN, numR, numN);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-10
        • 2012-07-17
        相关资源
        最近更新 更多