基于多个分隔符('\n','/')拆分文本

2024-04-26 04:14:58 发布

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

假设我有这样一个文档:

document = ["This is a document\nwhich has to be splitted\nOK/Right?"]

我希望在遇到“\n”或“/”时拆分此文档(用于开始)。你知道吗

因此,上述文件应转换为以下文件:

document = ["This is a document", "which has to be splitted", "OK", "Right?"]

我该怎么做?你知道吗

请记住,文本中可能有其他特殊字符等,我现在不想删除它们。你知道吗


Tags: 文件to文档文本rightwhichisok
3条回答

使用re.split()可能是最好的解决方案。你知道吗

没有正则表达式的替代解决方案:

document = ["This is a document\nwhich has to be splitted\nOK/Right?"]
document[0] = document[0].replace('/', '\n')
document[0].splitlines()

使用re根据多个字符或字符组合拆分文本字符串:

document = ["This is a document\nwhich has to be splitted\nOK/Right?"]
re.split("[\n/]",document[0])

它生成请求的字符串:

['This is a document', 'which has to be splitted', 'OK', 'Right?']

您可以使用re.split()

import re
def split_document(document):
    if document == []:
        return []
    tmp_str = document[0]
    tmp_list = re.split("\n|/",tmp_str)
    return tmp_list+split_document(document[1:])

相关问题 更多 >