在python中读取文件后返回单词列表 [英] returning a list of words after reading a file in python

查看:630
本文介绍了在python中读取文件后返回单词列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a text file which is named test.txt. I want to read it and return a list of all words (with newlines removed) from the file.

这是我当前的代码:

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()  

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

Running this code produces this list:

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

我希望列表看起来像这样:

I want the list to look like this:

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

推荐答案

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

Replace the words_list.append(...) line in the for loop with the following:

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

这会将每行分隔为空白字符,然后将结果列表的每个元素添加到words_list.

This will split each line on whitespace characters, and then add each element of the resulting list to words_list.

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

Or as an alternative method for rewriting the entire function as a list comprehension:

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

这篇关于在python中读取文件后返回单词列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆