简体   繁体   English

创建基本清单?

[英]Creation of basic lists?

I am trying to create a list in Python from a text file. 我正在尝试从文本文件在Python中创建一个列表。 I would like to open the file, read the lines, use the split method, append them to a list. 我想打开文件,阅读各行,使用split方法,将它们附加到列表中。 This is what I have so far. 到目前为止,这就是我所拥有的。 All it does is print the text file: 它所做的只是打印文本文件:

lines = []
folder = open("test.txt")
word = folder.readlines()
for line in word:
    var = ()
    for line in word:
        lines.append(line.strip().split(","))
        print (word)

My file looks like this: fat cat hat mat sat bat lap 我的文件看起来像这样: fat cat hat mat sat bat lap

I want this to come out: ['fat', 'cat', 'hat', 'mat', 'sat', 'bat', 'lap'] 我希望它出来: ['fat', 'cat', 'hat', 'mat', 'sat', 'bat', 'lap']

As other commentors have observed, variable naming should provide the context of what your variable is assigned to. 正如其他评论者所观察到的那样,变量命名应提供变量分配给的上下文 Even though you can name a variable a multitude of names, they should be relevant! 即使您可以为变量命名多个名称,它们也具有相关性!

You can use the with statement to open and close a file within the same scope, ensuring that the file object is closed ( generally good practice ). 您可以使用with语句在同一范围内打开和关闭文件,以确保关闭文件对象( 通常是一种好习惯 )。 From then on, you can print the lines returned from the readlines() function as a list that is split() based on a ' ' delimiter. 从那时起,您可以将readlines()函数返回的lines打印为基于' '分隔符的split() list

with open("test.txt") as file:
    lines = file.readlines()
for line in lines:
    print line.split(' ')

Sample output: 样本输出:

File: fat cat hat mat sat bat lap 文件: fat cat hat mat sat bat lap

>>> ['fat', 'cat', 'hat', 'mat', 'sat', 'bat', 'lap']

If your file only consists of one line then you don't need to do nearly as much work as you seem to think. 如果文件只包含一行,那么您不需要做看起来像想的那么多的工作。

str.split returns a list, so there is no need to append the individual elements. str.split返回一个列表,因此不需要append单个元素。 When you call .split() without any arguments it will split by any whitespace (spaces, tabs, newlines etc) so to do what you want to do would literally just be: 当您不带任何参数调用.split() ,它将被任何空格(空格,制表符,换行符等)分割,因此要执行的操作实际上就是:

with open("test.txt","r") as f:
    mywords = f.read().split()

print(mywords)

open the file, read the contents, split it up by whitespace, store the resulting list in a variable called mywords . 打开文件,读取内容,将其按空格分隔,将结果列表存储在名为mywords的变量中。 (or whatever you want to call it) (或任何您想调用的名称)

Note that spliting by any whitespace means it will treat new lines the same as spaces, just another separation of words. 请注意,通过任何空格分割意味着将将换行与空格相同,只是将单词分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM