【问题标题】:Splitting list elements after many delimiters在许多分隔符之后拆分列表元素
【发布时间】:2022-01-19 11:27:27
【问题描述】:

我想在选定的分隔符之后剪切列表元素(一次很多):'-'、',' 和 ':'

我有一个示例列表:


list_1 = ['some text – some another', 'some text, some another', 'some text: some another']

我想剪切列表元素(在这种情况下为字符串),以便它返回以下输出:

splitted_list = ['some text', 'some text', 'some text']

我已经尝试过 split() 但一次只需要 1 个分隔符:

splited_list = [i.split(',', 1)[0] for i in list_1]


我更喜欢对我来说更容易理解并且我可以决定使用哪个分隔符的东西。例如,我不想在- 之后而是在- 之后剪切字符串。

分隔符列表:

: -,

注意-前后有空格,: 只有在之后,就像, 一样。

【问题讨论】:

  • splited_list = [i.split(',', 1)[0].split('-', 1)[0].split(':', 1)[0] for i in list_1] 再次拆分新的“结果”或将 2 个 delim 替换为第三个并与之拆分:splited_list = [i.replace('-',',').replace(':',',').split(',', 1)[0] for i in list_1]

标签: python python-3.x regex list


【解决方案1】:

您可以在re.sub 中使用此正则表达式并将其替换为空字符串:

\s*[^\w\s].*

这将匹配 0 个或多个空格,后跟一个不是空格且不是单词字符的字符,以及后面的任何内容。

import re

list_1 = ['some text – some another', 'some text, some another', 'some text: some another']
delims = [',', ':', ' –']
delimre = '(' + '|'.join(delims) + r')\s.*'
splited_list = [re.sub(delimre, '', i) for i in list_1]

print (splited_list)

输出:

['some text', 'some text', 'some text']

【讨论】:

  • 是的,您的解决方案工作得非常好,尽管我更喜欢对我来说更容易理解并且我可以决定使用哪个分隔符的东西。例如,我不想在“-”之后而是在“-”之后剪切字符串。不要误会我的意思——你的代码非常好——谢谢你——我只是在寻找一个更易于管理的例子。
  • 请指定要包含的分隔符,并且可以轻松调整答案。
  • ': ' , ' - ' , ', ' 注意 ' - ' 前后有空格,': ' 只在之后,就像 ', ' 一样。这就是为什么我需要更易于管理的代码,我可以简单地添加它们。谢谢。
  • 好的,现在检查我的更新答案
  • anubhava 任何机会您都可以简要解释一下这段代码的作用 - delimre = '(' + '|'.join(delims) + r')\s.*'
猜你喜欢
  • 2018-05-19
  • 2018-03-12
  • 2020-06-10
  • 2013-06-07
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
相关资源
最近更新 更多