读取python文件后返回单词列表

2024-04-26 18:32:46 发布

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

我有一个名为test.txt的文本文件。我想阅读它并返回文件中所有单词的列表(删除换行符)

这是我当前的代码:

def read_words(test.txt):
    open_file = open(words_file, 'r')
    words_list =[]
    contents = open_file.readlines()
    for i in range(len(contents)):
         words_list.append(contents[i].strip('\n'))
    return words_list    
    open_file.close()  

运行此代码将生成以下列表:

['hello there how is everything ', 'thank you all', 'again', 'thanks a lot']

我希望列表如下所示:

['hello','there','how','is','everything','thank','you','all','again','thanks','a','lot']

Tags: 代码testtxthello列表iscontentsopen
3条回答

将for循环中的words_list.append(...)行替换为以下内容:

words_list.extend(contents[i].split())

这将在空格字符上拆分每一行,然后将结果列表的每个元素添加到words_list

或者作为将整个函数重写为列表的替代方法:

def read_words(words_file):
    return [word for line in open(words_file, 'r') for word in line.split()]

根据文件的大小,这似乎很容易:

with open(file) as f:
    words = f.read().split()

我是这样写的:

def read_words(words_file):
  with open(words_file, 'r') as f:
    ret = []
    for line in f:
      ret += line.split()
    return ret

print read_words('test.txt')

使用itertools可以稍微缩短函数,但我个人认为结果可读性较差:

import itertools

def read_words(words_file):
  with open(words_file, 'r') as f:
    return list(itertools.chain.from_iterable(line.split() for line in f))

print read_words('test.txt')

第二个版本的好处是,它可以完全基于生成器,从而避免将文件中的所有字同时保存在内存中

相关问题 更多 >