Python拆分字符串并将分隔符保留为单词

2024-05-29 09:41:10 发布

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

我尝试使用多个分隔符拆分字符串。我需要保持分隔符为单词。 我使用的分隔符是:所有标点符号和空格。在

例如,字符串:

Je suis, FOU et toi ?!

应产生:

^{pr2}$

我写道:

class Parser :
    def __init__(self) :
        """Empty constructor"""

    def read(self, file_name) :
        from string import punctuation
        with open(file_name, 'r') as file :
            for line in file :
                for word in line.split() :
                    r = re.compile(r'[\s{}]+'.format(re.escape(punctuation)))
                    print(r.split(word))

但我得到的结果是:

['Je']
['suis', '']
['FOU']
['et']
['toi']
['', '']

拆分似乎正确,但结果列表不包含分隔符:(


Tags: 字符串nameinselffordeflinetoi
1条回答
网友
1楼 · 发布于 2024-05-29 09:41:10

您需要将表达式放入一个组中,re.split()才能保留它。我不会先拆分空格;以后总是可以只删除空白字符串。如果要将每个标点符号分隔开,则应仅在\s空白组中使用+量词:

# do this just once, not in a loop
pattern = re.compile(r'(\s+|[{}])'.format(re.escape(punctuation)))

# for each line
parts = [part for part in pattern.split(line) if part.strip()]

列表理解将删除仅由空白组成的任何内容:

^{pr2}$

您还可以使用re.findall()查找所有单词标点序列,而不是拆分:

pattern = re.compile(r'\w+|[{}]'.format(re.escape(punctuation)))

parts = pattern.findall(line)

这样做的好处是不需要过滤掉空白:

>>> pattern = re.compile(r'\w+|[{}]'.format(re.escape(punctuation)))
>>> pattern.findall(line)
['Je', 'suis', ',', 'FOU', 'et', 'toi', '?', '!']

相关问题 更多 >

    热门问题