python - 将文件转换为列表的最快方法?

标签 python python-3.x list

我有一个 .txt 文件,其中包含一些词: 例如

bye

bicycle

bi
cyc
le

我想返回一个包含文件中所有单词的列表。我已经尝试了一些实际有效的代码,但我认为执行更大的文件需要花费很多时间。有没有办法让这段代码更有效率?

with open('file.txt', 'r') as f:
    for line in f:
        if line == '\n': --> #blank line 
            lst1.append(line)
        else:
            lst1.append(line.replace('\n', '')) --> #the way i find more efficient to concatenate letters of a specific word
    str1 = ''.join(lst1)
    lst_fin = str1.split()

预期输出:

lst_fin = ['bye', 'bicycle', 'bicycle']

最佳答案

我不知道这是否更有效,但至少它是一个替代方案......:)

with open('file.txt') as f:
    words = f.read().replace('\n\n', '|').replace('\n', '').split('|')
print(words)

...或者如果您不想在数据中插入像 '|' 这样的字符(可能已经存在),您也可以这样做

with open('file.txt') as f:
    words = f.read().split('\n\n')
    words = [w.replace('\n', '') for w in words]
print(words)

两种情况的结果是一样的:

# ['bye', 'bicycle', 'bicycle']

编辑:

我想我有另一种方法。但是,它要求文件不能以空行开头,iiuc...

with open('file.txt') as f:
    res = []
    current_elmnt = next(f).strip()
    for line in f:
        if line.strip():
            current_elmnt += line.strip()
        else:
            res.append(current_elmnt)
            current_elmnt = ''
print(words)

也许你想试一试...

关于python - 将文件转换为列表的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58814930/

相关文章:

python - 抓取链接和标题 - 使用 beautifulsoup 存储在字典中

python - 超出最大递归深度,但仅在使用装饰器时

python - 将 "\n"添加到文本中的特定行

c++ - 我在一些指针上遇到了问题,调试结束时访问位置失败

list - Prolog - 从列表中删除具有相同第一个值的对

python - 始终在 wcs 轴上显示整个刻度标签

python - Miniconda3 安装失败,错误 "python-3.7.1-h0371630_7/bin/python: not found"

python - os.path模块如何工作?

python - 使用 %matplotlib 内联时,Jupyter 笔记本 Canvas 无法交互

java - 如何在方法中流式传输 Java List (Varargs) 的值?