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

在Python中创建多个数据结构(dicts),python,dictionary,Python,Dictionary,新手程序员在这里。自学Python。关于Stackoverflow的第一个问题 我正试图写一个程序,根据用户对价格、等级和烹饪类型的选择推荐一家餐厅。为了实现这一点,该计划构建了三种数据结构:[我仍处于中间阶段] # Initiating the data structures name_rating = {} price_name = {} cuisine_name = {} 数据来自restaurants.txt,格式如下: #Rest name #Rest Rating #Rest P

新手程序员在这里。自学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)
下面返回一个名称字典:ratings

# 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 
下面返回一个price字典:name

# 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()
问:当我调用函数时,为什么只有我首先调用的函数才成功?第二个dict仍然是空的。如果我单独调用它们,数据结构就会被构建。如果我两者都打电话,只有第一个是成功的


p、 我相信我可以更快地完成这一切,但现在我正在尝试自己去做,所以有些可能看起来多余或不必要。请耐心听我说:)

您可以使用
seek
方法将文件位置设置为重新开始(请参阅):


当打开一个文档并在第一个函数中读取时,您到达了它的末尾,然后在第二个函数中,您试图读取的内容超过了结尾,因此这是不可能的。我认为这里没有明确提到的要点是,文件对象是有状态的,并且有一个光标(“位置”)它将向前移动,直到到达文件末尾,之后,您将无法读取更多数据,因此不会执行文件对象上的进一步
for
迭代。一种方法是建议的方法,但围绕这个问题还有其他方法:一种是在每个函数中重新打开文件。另一种方法是将文件读入内存缓冲区,然后对其进行操作,另一种方法是使用多路复用处理程序。文件重新打开/查找在这里很好,但无法缩放。
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