如何拆分一个字符串,以便在不使用regex的情况下将符号生成它们自己的列表项?

2024-04-26 12:15:00 发布

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

Jamies_string = "Hello there {my name is jamie}".split()

print(Jamies_string)

此处输出:

['Hello', 'there', '{my', 'name', 'is', 'jamie}']

此处显示所需输出:

['Hello', 'there', '{', 'my', 'name', 'is', 'jamie', '}']

我真的很想远离任何涉及使用re库的解决方案,谢谢。你知道吗


Tags: namerehellostringismy解决方案split
3条回答

一种解决方案是创建一个对字符进行分类的函数,并将其用作itertools.groupby()的键函数:

WHITESPACE = 0
LETTERS = 1
DIGITS = 2
SYMBOLS = 3

def character_class(c):
    if c.isspace():
        return WHITESPACE
    if c.isalpha():
        return LETTERS
    if c.isdigit():
        return DIGITS
    return SYMBOLS

s = "Hello there {my name is jamie}"
tokens = [
    "".join(chars)
    for cls, chars in itertools.groupby(s, character_class)
    if cls != WHITESPACE
]
print(tokens)

印刷品

['Hello', 'there', '{', 'my', 'name', 'is', 'jamie', '}']

您明确表示,出于性能原因,希望避免使用正则表达式。这个答案中的方法肯定比正确使用正则表达式慢。然而,我不认为你的项目是在一个阶段,你需要担心性能。你知道吗

您使用的字符串类似于Python中的format string。如果是这样,您可以使用^{}类来解析它:

from string import Formatter


def solve(s):
    for f in Formatter().parse(s):
        yield from f[0].split()
        if f[1]:
            yield from ['{'] + f[1].split() + ['}']

演示:

>>> list(solve("Hello there {my name is jamie}"))
['Hello', 'there', '{', 'my', 'name', 'is', 'jamie', '}']

>>> list(solve("Hello there {my name is jamie} {hello world} end."))
['Hello', 'there', '{', 'my', 'name', 'is', 'jamie', '}', '{', 'hello', 'world', '}', 'end.']

您可以先在这些符号周围添加空格,然后使用split(),例如

>>> s = "Hello there {my name is jamie}"
>>> s.replace("{", " { ").replace("}", " } ").split()
['Hello', 'there', '{', 'my', 'name', 'is', 'jamie', '}']

相关问题 更多 >