【问题标题】:Split by the delimiter that comes first, Python由首先出现的分隔符分割,Python
【发布时间】:2015-04-18 15:16:49
【问题描述】:

我尝试拆分一些不可预测的日志行。

我可以预测的一件事是,第一个字段总是以 .: 结尾。

有什么方法可以自动分割字符串在哪个分隔符先出现?

【问题讨论】:

  • 随机问题:他们使用 .或 : 对于字段分隔符以外的任何内容...如果不是,您可以执行 line.replace('.',":').split(":")
  • 其他领域完全无法预测,我得到了各种不同的东西。
  • 很公平......我只是想我会提供一个可能的班轮;下面的答案显然更复杂,但在面对不可预测的数据时更加稳健
  • 哦,谢谢。希望我能想出一个班轮,但我还没有发展这些技能。

标签: string python-2.7 parsing logfile


【解决方案1】:

使用index() 函数查看字符串中.: 字符的索引。

这是一个简单的实现:

def index_default(line, char):
    """Returns the index of a character in a line, or the length of the string
    if the character does not appear.
    """
    try:
        retval = line.index(char)
    except ValueError:
        retval = len(line)
    return retval

def split_log_line(line):
    """Splits a line at either a period or a colon, depending on which appears 
    first in the line.
    """
    if index_default(line, ".") < index_default(line, ":"):
        return line.split(".")
    else:
        return line.split(":")

我将 index() 函数包装在 index_default() 函数中,因为如果该行不包含字符,index() 会抛出一个 ValueError,而且我不确定您的日志中的每一行是否都包含句号和冒号。

下面是一个简单的例子:

mylines = [
    "line1.split at the dot",
    "line2:split at the colon",
    "line3:a colon preceded. by a dot",
    "line4-neither a colon nor a dot"
]

for line in mylines:
    print split_log_line(line)

返回

['line1', 'split at the dot']
['line2', 'split at the colon']
['line3', 'a colon preceded. by a dot']
['line4-neither a colon nor a dot']

【讨论】:

  • 您的回答似乎是解决问题的绝佳方法。我现在要试试这个,让你知道它是如何工作的。
  • 优秀!通过该功能传递了我的日志,效果很好!非常感谢!
【解决方案2】:

检查两个字符的索引,然后使用最低的索引来拆分字符串。

【讨论】:

  • 好主意。所以就像period = mystring.index('.')colon = mystring.index(':')if period &lt; colon: mystring.split('.') else: mystring.split(':')我会试试这个。
猜你喜欢
  • 2021-06-12
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2013-05-03
相关资源
最近更新 更多