我有一个 .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/