【问题标题】:Making a dictionary from a file [duplicate]从文件制作字典[重复]
【发布时间】:2011-11-14 20:17:40
【问题描述】:

可能重复:
Create a function that opens a file and creates a dictionary

我们被赋予了一个 main 函数用于:

编写以下两个函数:

  1. init_dictionary(file_string, sunspot_dict)
    此函数将要打开的文件名和一个空字典作为参数。它没有返回值,但确实用值填充字典。关键应该是年份;数据应该是当年月份的太阳黑子数据列表。

主要功能是:

def main():
sunspot_dict = {}
file_str = raw_input("Open what data file: ")
keep_going = True
while keep_going:
    try:
        init_dictionary(file_str, sunspot_dict)
    except IOError:
        print "Data file error, try again"
        file_str = raw_input("Open what data file: ")    
        continue
    print "Jan, 1900-1905:", avg_sunspot(sunspot_dict, (1900,1905),(1,1))
    print "Jan-June, 2000-2011:", avg_sunspot(sunspot_dict, (2000,2011), (1,6))
    print "All years, Jan:", avg_sunspot(sunspot_dict, month_tuple=(1,1))
    print "All months, 1900-1905:", avg_sunspot(sunspot_dict, year_tuple=(1900,1905))
    try:
        print "Bad Year Key example:", avg_sunspot(sunspot_dict, (100,1000), (1,1))
    except KeyError:
        print "Bad Key raised"
    try:
        print "Bad Month Index example:", avg_sunspot(sunspot_dict, (2000,2011), (1,100))
    except IndexError:
        print "Bad Range raised"
    keep_going = False
print "Main function finished normally."

我不知道从哪里开始!请帮忙!

给出的文件是 x 轴上的月份和 1749 年至 2011 年的年份,其中填有数字

【问题讨论】:

  • “我不知道从哪里开始!”您需要从某个地方开始,所以从打开和读取文件开始(如果您不知道如何,请搜索如何在 Python 中进行文件 I/O)。一旦遇到具体问题,提出问题,如果运气好的话,也许有人可以提供帮助。

标签: python


【解决方案1】:

详细了解 Python 中的 IO ....

您需要打开文件,提取其内容,然后填充您的字典...

看看Input-Output in Python

一个提示是看看这个例子,他们试图从一个文件中制作一个字典....reading file to dictionary

【讨论】:

  • 我需要年份作为年份的键,值作为数据,这里是一些txt文件:每月平均太阳黑子数=========== ==================================================== ================== 年份 1 月 2 月 3 月 4 月 5 月 6 月 7 月 8 月 9 月 10 月 11 月 12 月 ------------------- -------------------------------------------------- ---------- 1749 58.0 62.6 70.0 55.7 85.0 83.5 94.8 66.3 75.9 75.5 158.6 85.2 1750 73.3 75.9 89.2 88.3 90.0 100.0 85.4 103.0 91.2 65.7 65.7
  • 先写出读写文件的代码……然后你就明白了……制作字典并不难解析文件数据是……所以先这样做跨度>
  • file_str = raw_input("要打开什么文件:") def init_dictionary(file_str, sunspot_dict): line = open(file_str, "rU") sunspot_dict = {} for i in line: sunspot_dict[i ] 打印 sunspot_dict
  • 这样做... data = line.readlines() 读取文件后..现在数据包含文件的每一行...在数据中执行for循环并将元素解析为你想要...
猜你喜欢
  • 2021-07-16
  • 1970-01-01
  • 2010-12-20
  • 2019-06-19
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
相关资源
最近更新 更多