【问题标题】:Pythonic way of parsing this string?解析这个字符串的 Pythonic 方式?
【发布时间】:2014-01-23 15:46:47
【问题描述】:

我正在解析这个line-

0386          ; Greek # L&       GREEK CAPITAL LETTER ALPHA WITH TONOS

基本上,我需要 -

point = 0386
script = Greek

我就是这样做的,

point = line.split(";")[0].replace(" ","")
script = line.split("#")[0].split(";")[1].replace(" ","")

我不相信我正在做的事情是最pythonic的方式,有没有更优雅的方式来做到这一点?也许是正则表达式单行?

【问题讨论】:

    标签: python regex string python-2.7


    【解决方案1】:

    我会这样做:

    >>> s = "0386          ; Greek # L&       GREEK CAPITAL LETTER ALPHA WITH TONOS"
    >>> point = s.split(';')[0].strip()
    >>> point
    '0386'
    >>> script = s.split(';')[1].split('#')[0].strip()
    >>> script
    'Greek'
    

    请注意,您可以重复使用s.split(';')。所以也许把它保存到var 是个好主意:

    >>> var = s.split(';')
    >>> point = var[0].strip()  # Strip gets rid of all the whitespace
    >>> point
    '0386'
    >>> script = var[1].split('#')[0].strip()
    >>> script
    'Greek'
    

    【讨论】:

      【解决方案2】:

      map与未绑定方法str.strip一起使用:

      >>> line = '0386      ; Greek # L&   GREEK CAPITAL LETTER ALPHA WITH TONOS'
      >>> point, script = map(str.strip, line.split('#')[0].split(';'))
      >>> point
      '0386'
      >>> script
      'Greek'
      

      使用列表推导:

      >>> point, script = [word.strip() for word in line.split('#')[0].split(';')]
      >>> point
      '0386'
      >>> script
      'Greek'
      

      【讨论】:

      • 这看起来很简洁,虽然我不喜欢使用map
      • @GamesBrainiac,我添加了列表理解版本。
      • @GamesBrainiac 为什么不是map?它将如何影响性能?
      • @ComputerFellow LC 通常比 maps 快。
      • 这种速度差异应该无关紧要。列表推导通常比 map 更受欢迎,因为它们更容易阅读。
      【解决方案3】:

      如果你想要一个正则表达式单行:

      point, script = re.search("^(\d+)\s*;\s*(\S+)\s*.*$",s).groups()
      

      s 是你的字符串,当然你需要import re

      【讨论】:

      • ("^(.*)\s+;\s+(.*)\s+#.*$", s).groups() 为我工作。以上没有。
      • @ComputerFellow,您的正则表达式将数字与后面的空格匹配。但如果它对你有用,我很高兴!无论如何,这里的重点是展示如何在一行中使用正则表达式。
      【解决方案4】:
      >>> code, desc = line[:line.rfind('#')].split(';')
      >>> code.strip()
      '0386'
      >>> desc.strip()
      'Greek'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-20
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 2013-09-02
        • 1970-01-01
        相关资源
        最近更新 更多