拆分python字符串

2024-05-08 06:51:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个字符串,我想以一种非常特殊的方式拆分它。我想把它分成一个包含每个单独单词的列表,除了一组单词被一个特定字符包围的情况。例如,下面的字符串将被这样拆分。在

'Jimmy threw his ball through the window.'

变成

^{pr2}$

但是,我想要一个边界字符

'Jimmy |threw his ball| through the window.'

成为

['Jimmy', 'threw his ball', 'through', 'the', 'window.']

作为一个附加组件,我需要-,它可能出现在分组短语的外部,在拆分后出现在它内部,即

'Jimmy |threw his| ball -|through the| window.'

会变成

['Jimmy', 'threw his', 'ball', '-through the', 'window.']

如果没有很多复杂的for循环和if语句,我找不到一个简单的python方法来实现这一点。有没有简单的方法来处理这样的事情?在


Tags: the方法字符串列表方式情况window字符
3条回答

您可以使用正则表达式解析该格式,尽管您选择的分隔符使其相当难看!在

此代码查找由一对管道字符|组成的所有序列,其中包含零个或多个非管道字符,一个或多个既不是管道也不是空白的字符。在

import re

str = 'Jimmy |threw his| ball -|through the| window.'

for seq in re.finditer(r' \| [^|]* \| | [^|\s]+ ', str, flags=re.X):
    print(seq.group())

输出

^{pr2}$

这不是一个开箱即用的解决方案,但是这里有一个非常像Python的函数,它可以处理你扔给它的几乎所有东西。在

def extract_groups(s):
    separator = re.compile("(-?\|[\w ]+\|)")
    components = separator.split(s)
    groups = []
    for component in components:
        component = component.strip()
        if len(component) == 0:
            continue
        elif component[0] in ['-', '|']:
            groups.append(component.replace('|', ''))
        else:
            groups.extend(component.split(' '))

    return groups

举个例子:

^{pr2}$

可能有一些正则表达式可以解决您的问题。你可以从下面的例子中得到这个想法:

import re
s = 'Jimmy -|threw his| ball |through the| window.'
r = re.findall('-?\|.+?\||[\w\.]+', s)
print r
print [i.replace('|', '') for i in r]

输出:

^{pr2}$

说明:

  • -?可选减号
  • \|.+?\|之间至少有一个字符的管道
  • |
  • [\w\.]+至少一个“word”字符或.

如果,或{}可以出现在原始字符串中,则需要对表达式进行一些微调。在

相关问题 更多 >