4

在调用readlines().srt 文件时,我得到了一个包含大量前导和尾随空格的字符列表,如下所示

with open(infile) as f:
    r=f.readlines()
    return r

我得到了这份清单

['\xef\xbb\xbf1\r\n', '00:00:00,000 --> 00:00:03,000\r\n', "[D. Evans] Now that you've written your first Python program,\r\n",'\r\n', '2\r\n', '00:00:03,000 --> 00:00:06,000\r\n', 'you might be wondering why we need to invent new languages like Python\r\n', '\r\n']

为简洁起见,我只包含了一些元素。如何清理此列表,以便删除所有空白字符并仅获取相关元素,例如

 ['1','00:00:00,000 --> 00:00:03,000',"[D. Evans] Now that you've written your first Python program"...]
4

1 回答 1

11

您可以剥离每一行。如果您正在处理一个大文件,将其作为生成器运行也可以为您节省一些内存。

此外,看起来您正在处理一个带有 BOM 的 UTF-8 文件(这有点愚蠢,或者至少是不必要的),因此您需要以不同的方式打开它。

import codecs

def strip_it_good(file):
    with codecs.open(file, "r", "utf-8-sig") as f:
        for line in f:
            yield line.strip()
于 2012-05-18T16:51:39.437 回答