我是靠谱客的博主 自信发带,最近开发中收集的这篇文章主要介绍python中.read()返回的是列表吗_在python中读取文件后返回单词列表,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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.

This is my current code:

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']

解决方案

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

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

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中.read()返回的是列表吗_在python中读取文件后返回单词列表的全部内容,希望文章能够帮你解决python中.read()返回的是列表吗_在python中读取文件后返回单词列表所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部