使用特定字符在Python中拆分字符串

2024-09-29 18:36:52 发布

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

我正在尝试将输入的文档按特定字符拆分。我需要在[和]把它们分开,但我很难搞清楚。

def main():
for x in docread:
    words = x.split('[]')
    for word in words:
        doclist.append(word)

这是代码的一部分,将它们拆分到我的列表中。但是,它将返回文档的每一行。

例如,我想转换

['I need to [go out] to lunch', 'and eat [some food].']

['I need to', 'go out', 'to lunch and eat', 'some food', '.']

谢谢!


Tags: andtoin文档goforfoodsome
3条回答

string.split(s)是您正在使用的字符串,它将“s”的整个内容视为分隔符。换言之,你的输入应该看起来像“[]我需要出去吃午饭”,“吃点东西给你想要的结果”。

您需要使用re module中的split(s),它将把s视为regex

import re

def main():
for x in docread:
    words = re.split('[]', x)
    for word in words:
        doclist.append(word)

您可以尝试使用re.split()代替:

>>> import re
>>> re.split(r"[\[\]]", "I need to [go out] to lunch")
['I need to ', 'go out', ' to lunch']

看起来很奇怪的正则表达式[\[\]]是一个字符类,它意味着在上拆分[]。内部\[\]必须是反斜杠转义,因为它们使用与[]相同的字符来包围字符类。

str.split()在传递给它的精确字符串处拆分,而不是在它的任何字符处拆分。传递"[]"将在出现[]时拆分,但不会在单个括号中拆分。可能的解决方案是

  1. 拆分两次:

    words = [z for y in x.split("[") for z in y.split("]")]
    
  2. 使用re.split()

相关问题 更多 >

    热门问题