Python中更好的行删除?

2024-04-20 07:33:44 发布

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

我分析了来自许多来源的文本数据,我需要删除空白行,不管行结束是\r\n,还是只是\n,但是下面的丑陋方法是我找到的唯一的方法来清理它们之间的空格。这是我正在使用的代码。我知道这不是最好的方法,但到目前为止我已经和regex划清界限了。最好的办法是什么?你知道吗

    text = text.replace('\r', '[EOL]')
    text = text.replace('\n', '[EOL]')
    for x in range(0, 30):
        text = text.replace("[EOL]        [EOL]", "[EOL]")
        text = text.replace("[EOL]       [EOL]", "[EOL]")
        text = text.replace("[EOL]      [EOL]", "[EOL]")
        text = text.replace("[EOL]     [EOL]", "[EOL]")
        text = text.replace("[EOL]    [EOL]", "[EOL]")
        text = text.replace("[EOL]   [EOL]", "[EOL]")
        text = text.replace("[EOL]  [EOL]", "[EOL]")
        text = text.replace("[EOL] [EOL]", "[EOL]")
        text = text.replace("[EOL][EOL]", "[EOL]")
    text = text.replace("[EOL]", "\r\n")

Tags: 数据方法代码textin文本for来源
2条回答

对于定义为看不到文本的任何行的“空白”行,请尝试

查找(?m)$\s+^
替换\r\n

你需要使用re.sub

re.sub(r'[\r\n]+[ \t]*[\r\n]*', r'\n', text)

相关问题 更多 >