0

如何将城市、时间、本地链接到一个搜索。就像我有一个被调用的函数一样,search它将仅在整个列表中搜索 city2 并仅打印值 City2、Time2、Local2?当我阅读文件并将其放入列表时,我需要做些什么吗?

*更新 * 无论如何要重写此代码,以便您拥有 3 个属性(城市、时间、本地)并将文件中的数据保存到列表中的对象中?并使用 str 函数打印它们?

示例列表

City
Time
Local
--------------
City2
Time2
Local2
--------------
City
Time
Local
--------------
City3
Time3
Local3
--------------

代码:

class gym:
def __init__(self, city, local, time,  ):
    self.city = city
    self.local = local
    self.time = time
    self.city_dict = {}

    def readfile():
        row = "start"
        list = []
        infile = open("data.txt", "r", encoding="utf-8")
        while row != "":
            row = infile.readline()
            list.append(rad)
        infile.close()

gym.readfile()
4

2 回答 2

3

我认为最简单的解决方案是一次读取整个文件并在不同的分隔符上拆分不同的部分。为了使您的搜索工作,您需要创建一个从city值到其他值的字典映射。

from collections import defaultdict

class gym():
    def __init__(self):
        self.city_dict = defaultdict(list)

    def readfile(self):
        with open("data.txt", encoding="utf-8") as infile:
            text = infile.read() # consumes the whole file into a string

        text = text.rstrip('-\n') # strip off any trailing dashes or newlines

        # split twice, first on dashed lines, then on newline characters
        data = [g.strip().split('\n') for g in text.split('--------------')]

        # now, store in dictionary for searching
        for city, time, local in data:
            self.city_dict[city].append((city, time, local))

    def search(self, city):
        for group in self.city_dict[city]:
             print(*group)
于 2013-09-07T13:01:46.970 回答
1

Blckknght 为您提供了一个很好的解决方案,如果您想对数据做其他事情,这将非常有用,但是对于您描述的任务 - 找到“City2”并打印它,以及它的时间和本地, - 你可以做到使用简单的grep -A2 City2 data.txt,或者使用 Python:

with open("data.txt", encoding="utf-8") as fh:
    for line in fh:
        if line.startswith("City2"):
            for _ in range(3):
                print(line.strip())
                line = next(fh)
            continue

如果您只想查找第一个匹配项,您可以替换continuebreak.

正如评论中所讨论的,您不必立即打印结果。你可以这样做:

matches = []
with open("data.txt") as fh:
    for line in fh:
        if line.startswith("City2"):
            matches.append([])
            for _ in range(3):
                matches[-1].append(line.strip())
                line = next(fh)
            continue
for match in matches:
    print("City: {}; Time: {}; Local: {}".format(*match))
于 2013-09-07T13:40:18.037 回答