在Python中创建多个数据结构(字典)

5

我是一名初学者程序员,正在自学Python。这是我在StackOverflow上的第一个问题。

我正在尝试编写一个程序,根据用户选择的价格、评分和菜系类型来推荐餐厅。为了实现这个目标,程序构建了三个数据结构:[我仍然处于中级阶段]

# Initiating the data structures

name_rating = {}
price_name = {}
cuisine_name = {}

数据来自于格式化为以下形式的 restaurants.txt 文件:
#Rest name
#Rest Rating
#Rest Price range
#Rest Cuisine type
#
#Rest2 name

以下函数仅返回所需行的字符串。
# The get_line function returns the 'line' at pos (starting at 0)
def get_line(pos):
    fname = 'restaurants.txt'
    fhand = open(fname)
    for x, line in enumerate(fhand):
        line = line.rstrip()
        if not pos == x: continue
        return line


# Locating the pos's of name, rate, price & cuisine type for each restaurant
# Assumes uniform txt file formatting and unchanged data set 

name_pos = [x for x in range(0,84,5)]
rate_pos = [x for x in range(1,84,5)]
price_pos = [x for x in range(2,84,5)]
cuis_pos = [x for x in range(3,84,5)]

每次增加5以便为每个餐厅单独获取数据。

fname = 'restaurants.txt'
fhand = open(fname)

以下返回一个名称:评分的字典。
# Builds the name_rating data structure (dict)
def namerate():
    for x, line in enumerate(fhand):
        line = line.rstrip()
        for n, r in zip(name_pos, rate_pos):
            if not n == x: continue
            name_rating[line] = name_rating.get(line, get_line(r))
    return name_rating 

以下代码返回一个价格:名称的字典。
# Builds the price_name data structure (dict)
def pricename():
    for x, line in enumerate(fhand):
        line = line.rstrip()
        for p, n in zip(price_pos, name_pos):
            if not p == x: continue
            price_name[line] = price_name.get(line, get_line(n))
    return price_name

调用函数
print pricename()
print namerate()

问题:当我调用函数时,为什么只有第一个被调用的成功了?第二个字典保持为空。如果我分别调用它们,数据结构就会建立。如果我同时调用两个,只有第一个成功。

p.s. 我相信我可以更快地完成所有这些工作,但现在我正在尝试自己做一些,因此有些可能显得冗余或不必要。请耐心等待 :)


2
当打开一个文档并在第一个函数中读取时,你到达了它的结尾,然后在第二个函数中,你试图读取超过结尾的内容,所以这是不可能的。 - Ruben Bermudez
1个回答

1
你可以使用seek方法将文件位置重新设置为起始位置(请参见文档):
f = open("test.txt")

for i in f:
    print(i)
# Print: 
    # This is a test first line
    # This is a test second line

for i in f:
    print(i)
# Prints nothig   

f.seek(0) # set position to the beginning

for i in f:
    print(i)
# Print: 
    # This is a test first line
    # This is a test second line

我认为这里尚未明确提到的显著点是文件对象具有状态并且具有光标(“位置”),该光标向前移动,直到达到文件结尾,此后,您将无法读取任何更多数据,因此文件对象上进一步的for迭代将不会被执行。一种方法是建议的方法,但是还有其他解决此问题的方法:一种方法是在每个函数中简单地重新打开文件。另一种方法是将文件读入内存缓冲区,然后对其进行操作,另一种方法是具有复用处理程序。文件重新打开/寻找在这里很好,但不会扩展。 - Preet Kukreti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接