【问题标题】:Split a string using a list of value at the same time同时使用值列表拆分字符串
【发布时间】:2019-05-05 00:20:56
【问题描述】:

我有一个字符串和一个列表:

src = 'ways to learn are read and execute.'
temp = ['ways to','are','and']

我想要的是使用列表temp 的值拆分字符串并生成:

['learn','read','execute']

同时。

我试过for循环:

for x in temp:
    src.split(x)

这是它产生的:

['','to learn are read and execute.']
['ways to learn','read and execute.']
['ways to learn are read','execute.']

我想要的是先输出列表中的所有值,然后用它拆分字符串。

有人有解决办法吗?

【问题讨论】:

  • 为什么所需的输出在'execute' 的末尾不包含一个点?
  • @timgeb 感谢提醒,其实点也不是我想要的。我忘了指定。

标签: python string python-3.x split


【解决方案1】:

re.split 是在多个分隔符上拆分的常规解决方案:

import re

src = 'ways to learn are read and execute.'
temp = ['ways to','are','and']

pattern = "|".join(re.escape(item) for item in temp)
result = re.split(pattern, src)
print(result)

结果:

['', ' learn ', ' read ', ' execute.']

您还可以通过简单的列表理解过滤掉空白项并去除空格+标点符号:

result = [item.strip(" .") for item in result if item]
print(result)

结果:

['learn', 'read', 'execute']

【讨论】:

  • Nitpick:如果单词包含 temp 元素之一,这可能会拆分单词。
  • @tobias_k 嗯,是的。如果这是不受欢迎的行为,也许您可​​以在模式中使用单词边界:pattern = "|".join("\\b" + re.escape(item) + "\\b" for item in temp)
  • 我会说这取决于temp 来决定。如果您想要词边界,请使用temp 中的\bs。
  • 可能还希望:pattern = "|".join(re.escape(item) for item in sorted(temp, key=len, reverse=True)) 先拆分最长的完整模式...
  • @Kevin 感谢您的回答。现在我明白它是如何工作的,您是否添加了| 以将列表转换为字符串并告诉re.split() 使用列表temp 中的所有或任何值进行拆分?
【解决方案2】:

这是一种纯粹的pythonic方法,不依赖于正则表达式。它更冗长、更复杂:

result = []
current = 0
for part in temp:
    too_long_result = src.split(part)[1]
    if current + 1 < len(temp): result.append(too_long_result.split(temp[current+1])[0].lstrip().rstrip())
    else: result.append(too_long_result.lstrip().rstrip())
    current += 1
print(result)

如果您不想删除列表条目中的尾随和前导空格,则不能删除 .lstrip().rstrip() 命令。

【讨论】:

    【解决方案3】:

    循环解决方案。您可以根据需要添加条带等条件。

    src = 'ways to learn are read and execute.'
    temp = ['ways to','are','and']
    copy_src = src
    result = []
    for x in temp:
        left, right = copy_src.split(x)
        if left:
            result.append(left) #or left.strip()
        copy_src = right
    result.append(copy_src) #or copy_src.strip()
    

    【讨论】:

    • 如果x 出现的次数多于或少于一次,则会失败。
    【解决方案4】:

    保持简单

    src = 'ways to learn are read and execute.'
    temp = ['ways','to','are','and']
    res=''
    for w1 in src.split():
      if w1 not in temp:
        if w1 not in res.split():
          res=res+w1+" "
     print(res)
    

    【讨论】:

    • 这并没有真正满足 OP 的要求,丢弃“方式”和“至”而不仅仅是“方式”,删除重复项并将其余部分连接回一个字符串。而且,效率相当低。至少将temp 设置为set,如果您想拥有唯一的单词,也可以使用set 代替res,最后使用' '.join
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2019-05-07
    • 2014-10-14
    • 2020-04-14
    相关资源
    最近更新 更多