【问题标题】:Parse elements from a text string (in a list)从文本字符串中解析元素(在列表中)
【发布时间】:2023-04-03 11:38:01
【问题描述】:

我有一个列表元素,它是文本。

print ((temp_list))

输出:

['root     pts/3        100.121.17.73    Tue Aug  7 14:22 - 14:23  (00:00)    ']

我希望得到这个输出:

Aug 7 14:23

我尝试删除空格,但这会弄乱输出,这使得分离出我想要的元素变得更加困难。

【问题讨论】:

  • 到目前为止,除了删除空格,您还尝试过什么?
  • temp_list[0].replace(" ","") 我试过这个
  • 为什么您的列表中只有一项?
  • 谢谢。你的解决方案有效

标签: python


【解决方案1】:
sample = 'root     pts/3        100.121.17.73    Tue Aug  7 14:22 - 14:23  (00:00)    '

# split the string on space characters
data = sample.split(' ')

# inspect our list in console, the list should now contain mix of words and spaces (empty string)
print(data)

# since empty string evaluates to False in Python, we can remove them like this from our list with filter function
data = filter(lambda x: x, data)


# outputs: ['root', 'pts/3', '100.121.17.73', 'Tue', 'Aug', '7', '14:22', '-', '14:23', '(00:00)']
print(data)

# in the end we collect relevant data by slicing the list
# from index 3rd to 6th and join them into one string with that data separated by one space in-between.
result = ' '.join(data[3:6])

# outputs: Tue Aug 7
print(result)

【讨论】:

  • 请编辑您的答案以添加对您的代码如何工作以及它如何解决 OP 问题的解释。许多 StackOverflow 用户是新手,不会理解您发布的代码,因此不会从您的回答中学习。
  • @ialarmedalien 注意到
  • 它也会被标记为低质量(这是我看到的)并且可能会被删除。
  • @ialarmedalien 好吧,为什么质量低?,其余的没有留下更多信息,我发布了最简单的答案,一个可以用基本 python 理解的答案。我不想在这里留下不好的内容,这不是我的意图,如果您认为它有任何不好的地方,请删除它。如果需要,可以随时询问更多细节,不是吗?
  • 不幸的是,许多来到这里的人甚至没有基本的python,对于经验丰富的程序员来说似乎很明显的东西对于新手来说就像黑魔法一样。通常人们只是复制并粘贴一个答案而不了解代码中发生了什么,他们会再次提出非常相似的问题,因为他们没有从他们使用的先前答案中学到任何东西。评论的答案非常好 - 赞成。 :)
【解决方案2】:

或者:

l=['root     pts/3        100.121.17.73    Tue Aug  7 14:22 - 14:23  (00:00)    ']
print(' '.join(l[0].split()[-6:][:-1]))

输出:

Aug  7 14:22 - 14:23 

【讨论】:

    【解决方案3】:

    如果你的字符串中总是有“Tue Aug 7 14:22 - 14:23”这种模式,那么我建议你使用正则表达式来匹配这个模式:

    import re
    
    temp_list = ['root     pts/3        100.121.17.73    Tue Aug  7 14:22 - 14:23  (00:00)    ']
    
    m = re.search(r'\w{3} +(\w{3}) +(\d{1,2}) +\d\d:\d\d +- +(\d\d:\d\d)', temp_list[0])
    
    result = ' '.join([m.group(i) for i in (1,2,3)])
    
    print(result)  # Aug 7 14:23
    

    【讨论】:

    • 不客气。请考虑接受这个答案。
    【解决方案4】:

    使用正则表达式。

    import re
    temp_list = ['root     pts/3        100.121.17.73    Tue Aug  7 14:22 - 14:23  (00:00)    ']
    
    for i in temp_list:
        m = re.search(r"(?P<date>(Jun|Jul|Aug|Sep).*?)\(", i)
        if m:
            print(m.group('date'))
    

    输出:

    Aug  7 14:22 - 14:23 
    

    【讨论】:

    • 其他月份在哪里?
    • 我刚刚添加了一个示例
    • “有时有效”的解决方案比没有解决方案更糟糕
    【解决方案5】:

    可以拆分文本,得到第5、6、9个字段:

    f = temp_list[0].split()
    print(' '.join((f[4], f[5], f[8])))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2021-10-21
      • 2017-08-06
      • 2016-12-05
      • 1970-01-01
      相关资源
      最近更新 更多