0

我怎样才能重写这个程序,所以我把所有的 data.txt 放到一个列表中,这样我就可以在城市之后搜索并使用列表对象和属性获取该城市的时间和本地时间?

数据.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()
4

4 回答 4

1
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-07T18:23:51.383 回答
1

我会读取整个文件并将其拆分为如下字符串:

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

最后分配你班级的变量:

for item in lst3:
    self.city, self.time, self.local = item
于 2013-09-07T18:09:32.593 回答
0

如果文件保持这种简单严谨的结构,这将起到作用:

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', '')

列表的.index()方法返回特定string(实际上是任何对象或不可变类型)的最早实例的索引。

于 2013-09-07T18:08:32.280 回答
0

关键思想:您希望分部分处理文件,每个部分具有相同的行数。因此,让我们编写一个通用方法来做到这一点:

def section_reader(file_name, n):
    # Takes a file name and an integer.
    # Will yield sections, each with N lines, until the file is exhausted.
    with open(file_name) as fh:
        while True:
            section = [fh.readline() for _ in xrange(n)]
            if len(section[0]): yield section
            else:               return

有了这些,剩下的代码就变得非常无聊了:一个类定义,一个清理节中行的实用方法,等等。

class City(object):
    def __init__(self, name, time, local):
        self.name  = name
        self.local = local
        self.time  = time

def clean(section):
    return [line.strip() for line in section[0:3]]

cities = [ City(*clean(s)) for s in section_reader('data.txt', 4) ]

for c in cities:
    print [c.name, c.local, c.time]
于 2013-09-07T19:57:23.447 回答