我如何重写这个程序,以便将所有的data.txt都放到列表中,这样我就可以搜索城市,并使用list对象和属性获得城市的时间和本地信息。
Data.txt
City1
Time1
Local1
--------------
City2
Time2
Local2
--------------
City
Time
Local
--------------
City3
Time3
Local3
--------------程序
class store:
def __init__(self, city, time, local):
self.city = city
self.time = time
self.local = local
def readfile():
row = "start"
list = []
infile = open("data.txt", "r", encoding="utf-8")
while row != "":
row = infile.readline()
list.append(rad)
infile.close()
store.readfile()发布于 2013-09-07 18:23:51
class City(object):
def __init__(self, name, time, local):
self.name = name
self.local = local
self.time = time
class Store(object):
def __init__(self):
self.data = {}
def readfile(self, filename):
with open(filename, 'r') as datafile:
subdata = []
for line in datafile:
if line.startswith('----'):
city = City(subdata[0], subdata[1], subdata[2])
self.data[subdata[0]] = city
subdata = []
else:
subdata.append(line.rstrip())
def city_named(self, city_name):
return self.data[city_name]
store = Store()
store.readfile('Data.txt')
example_city = store.city_named('City1')
print(example_city.name)
print(example_city.time)
print(example_city.local)发布于 2013-09-07 18:09:32
我将读取整个文件并将其拆分为如下字符串:
with open('data.txt') as f:
lst = f.read().split()然后过滤掉破折号线:
lst = [s for s in lst if not s.startswith('-')]然后将字符串拆分为三组,前提是字符串的数目可被分割为3:
lst3 = [lst[i:i+3] for i in range(0, len(lst), 3)]最后,分配您类的vars:
for item in lst3:
self.city, self.time, self.local = item发布于 2013-09-07 18:08:32
如果文件保持这种简单、严格的结构,这将起到以下作用:
def info_from_city(file,city):
city += '\n'
list = fh.readlines()
city_index = list.index(city)
time_index = list[city_index+1]
local_index = list[city_index+2]
return (time_index,local_index)
fh = open('data.txt')
print 'Time and local:'
print info_from_city(fh,'City2')产出如下:
Time and local:
('Time2\n', 'Local2\n')(请注意换行符--您可能希望使用.replace('\n', '')处理掉它们)
list的.index()方法返回特定string的最早实例的索引(实际上是任何对象或不可变类型)。
https://stackoverflow.com/questions/18676293
复制相似问题