[英]python creating a list from lines in a file
I need to create a list of strings for each line in a file. 我需要为文件中的每一行创建一个字符串列表。
Example: 例:
This is my file.
These are examples.
would create: ['This', 'is', 'my', 'file'] ['These', 'are', 'examples'] 会创建:['This','is','my','file'] ['These','are','examples]]
I need to do this because I am trying to translate a file into a pig latin file. 我需要执行此操作,因为我正在尝试将文件转换为猪拉丁文件。
Split each line in the file along the space character and retrieve it as a list. 沿着空格字符分割文件中的每一行,并将其作为列表检索。
f = open('filename.txt', 'r')
li = [line.split() for line in f]
Try this: 尝试这个:
res = []
with open(filename, 'r') as f:
for line in f:
res.append(line.split())
OR: 要么:
map(str.split, open(filename, 'r'))
If you need to get rid of dots: 如果您需要去除点:
res = []
with open(filename, 'r') as f:
for line in f:
res.append(line.strip('.').split())
You can also use the readLines 您也可以使用readLines
f = open('file.txt', 'r')
lines = [line.split(' ') for line in f.readlines()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.