[英]How to put certain instances of a text file to a list in python
This is what a part of the txt file looks like:这是 txt 文件的一部分:
3/Kingsbury Dr/Waterdale Rd/Bundoora 3/Kingsbury Dr/Waterdale Rd/Bundoora
4/Crissane Rd/Waterdale Rd/Heidelberg West 4/Crissane Rd/Waterdale Rd/海德堡西
I just want to get the second element which is the bus stop (eg Kingsbury Dr, Crissane Rd) instance in a list.我只想获取列表中的第二个元素,即公交车站(例如 Kingsbury Dr、Crissane Rd)实例。 Here is what I have tried so far and not sure how to put the second element in a list
这是我到目前为止所尝试的,但不确定如何将第二个元素放入列表中
def loadData():
with open('BusRoute250.txt', 'r') as f:
busStopList = []
f_line = f.readline()
while f_line:
file_line_lst = list(f_line.strip().split('/'))
f_line = f.readline()
for f_line in file_line_lst:
busStopList.append()
print(busStopList)
The link for txt file contents: https://docs.google.com/document/d/1ah1EAhro_5-pgqIDylFSjTyHI9fvylfErB8pFNZb36A/edit?usp=sharing txt 文件内容的链接: https : //docs.google.com/document/d/1ah1EAhro_5-pgqIDylFSjTyHI9fvylfErB8pFNZb36A/edit? usp =sharing
You need to add the second element of the list formed in the result of split('/')
operation.您需要添加
split('/')
操作结果中形成的列表的第二个元素。
busStopList.append(file_line_lst[1])
The while
loop is a bit wrong. while
循环有点错误。 It should be like this:应该是这样的:
while f_line:
file_line_lst = list(f_line.strip().split('/'))
busStopList.append(file_line_lst[1])
f_line = f.readline()
Try this:尝试这个:
def loadData():
with open('BusRoute250.txt', 'r') as f:
bus_stops = []
for line in f:
elements = line.strip().split('/')
if len(elements) > 0:
bus_stops.append(elements[1])
return bus_stops
#call function and print:
result = loadData()
print('\n'.join(result)) # print as a column
You do not need to explicitly call readline
for this purpose.为此,您无需显式调用
readline
。 Here we will use a for loop to iterate the file one line at a time, check that the line contains fields, and build the list from each of the second fields.在这里,我们将使用 for 循环一次一行地迭代文件,检查该行是否包含字段,并从每个第二个字段构建列表。
This is an approach that does not call for external libraries.这是一种不需要外部库的方法。 But if you plan to do any amount of work with delimited text, I would suggest starting to learn Python
pandas
.但是,如果您打算对带分隔符的文本进行任何工作,我建议您开始学习 Python
pandas
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.