首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python 3.x需要帮助将一个文本文件拆分为4个字典

python 3.x需要帮助将一个文本文件拆分为4个字典
EN

Stack Overflow用户
提问于 2016-07-19 12:13:02
回答 2查看 37关注 0票数 0

有人能帮我解决我遇到的问题吗?我正在试着写一些代码,可以让用户选择特定的文件,然后将其与当前的技能水平进行比较,每个文件都有一个简单、中等、困难和精英的部分,我想把它们放在单独的字典中,我可以让它打印整个文件的正确信息,但我想不出如何将它分成4个单独的字典

代码语言:javascript
复制
# shows all osrs diarys 
def diary_selection():
    diary_options = {
    0 : 'ardougne', 1 : 'desert', 2 : 'falador', 3 : 'fremennik', 4 : 'kandarin',
    5 : 'lumbridge', 6 : 'morytania', 7 : 'varrock', 8 : 'western', 9 : 'wilderness'
    }
    print(diary_options)

# if not a correct number gives prompt to retry  
    while True:
        try:
            d_sel = int(input ("\nType in the number next to the diary: "))
            diary_select = d_sel

            if not (0 < diary_select > 9):
                print('option is valid')
                break
            else:
                print(" invalid option.")
                diary_selection()

        except ValueError:
            print(" invalid option, numbers only, please try again.")


# gets the name of the diary acording to what number was pressed
    current_diary = diary_options.get(diary_select)

#creats a filename for spicific diary        
    diary_file_name = str((current_diary + "_diary.txt"))
    print (diary_file_name,"\n")

#searches for file name in folder ./diary_requirements     
    f = open("./diary_requirements/"+diary_file_name,"r")
    file_contents = f.read()


    return file_contents

我试图操作的文件被组织在一个txt文件中,格式为简单、中等、困难、精英级别。

代码语言:javascript
复制
easy_levels = {
"Attack" : 0
, "Defense" : 0
, "Strength" : 0
, "Hitpoints": 0
, "Range" : 30
, "Prayer" : 0
, "Magic" : 0
, "Cooking" : 0
, "Woodcutting" : 0
, "Fletching" : 20
, "Fishing" : 0
, "Firemaking" : 0
, "Crafting" : 0
, "Smithing" : 0
, "Mining" : 15
, "Herblore" : 0
, "Agility" : 0
, "Thieving" : 0
, "Slayer" : 0
, "Farming" : 0
, "Runecrafting" : 0
, "Hunting": 9
, "Construction" : 0
,
}
medium_levels = {
"Attack" : 0
, "Defense" : 0
, "Strength" : 0
, "Hitpoints": 0
, "Range" : 30
, "Prayer" : 0
, "Magic" : 0
, "Cooking" : 42
, "Woodcutting" : 35
, "Fletching" : 5
, "Fishing" : 46
, "Firemaking" : 35
, "Crafting" : 0
, "Smithing" : 0
, "Mining" : 40
, "Herblore" : 0
, "Agility" : 37
, "Thieving" : 0
, "Slayer" : 0
, "Farming" : 0
, "Runecrafting" : 0
, "Hunting": 31
, "Construction" : 0
,
}
EN

回答 2

Stack Overflow用户

发布于 2016-07-19 13:39:29

我猜你唯一的困难就是如何根据你所描述的结构填写四本字典。

如果您确定这些文件不会被除您以外的任何人更改,并且您可以使用不安全和肮脏的代码,您可以这样做:

代码语言:javascript
复制
exec(file_contents)

这样做的目的是,由于您的文件结构的内容已经是有效的python,所以它在被调用的作用域中执行它。因此,在执行它之后,您可以访问调用它的作用域中的变量easy_levels, medium_levels, hard_levels, elite_levels。请注意,这假设您在尝试访问的任何日记中都正确定义了这些变量,如果每个日记定义的变量可能会发生变化,您应该使用更安全的方法(或丑陋的快速访问locals())。

票数 0
EN

Stack Overflow用户

发布于 2016-07-19 13:54:40

试试这个:

代码语言:javascript
复制
import os
import imp
from pprint import pprint

# shows all osrs diarys 
def diary_selection():
    diary_options = {
    0 : 'ardougne', 1 : 'desert', 2 : 'falador', 3 : 'fremennik', 4 : 'kandarin',
    5 : 'lumbridge', 6 : 'morytania', 7 : 'varrock', 8 : 'western', 9 : 'wilderness'
    }
    print(diary_options)

    # if not a correct number gives prompt to retry  
    while True:
        try:
            d_sel = int(input ("\nType in the number next to the diary: "))
            diary_select = d_sel

            if diary_select in diary_options:
                print('option is valid')
                break
            else:
                print(" invalid option.")
                #diary_selection()

        except ValueError:
            print(" invalid option, numbers only, please try again.")


    # gets the name of the diary acording to what number was pressed
    current_diary = diary_options.get(diary_select)

    #creats a filename for spicific diary        
    diary_file_name = str((current_diary + "_diary.txt"))
    print (diary_file_name,"\n")

    #searches for file name in folder ./diary_requirements     
    #f = open("./diary_requirements/"+diary_file_name,"r")
    #file_contents = f.read()
    #return file_contents

    foo = imp.load_source('userInfo', os.getcwd() + '/diary_requirements/' + diary_file_name)
    print('{}\nEasy levels\n{}'.format('-'*40, '-'*40))
    pprint(foo.easy_levels)
    print('{}\nMediyum levels\n{}'.format('-'*40, '-'*40))
    pprint(foo.medium_levels)

diary_selection()

输出(python ):

代码语言:javascript
复制
{0: 'ardougne', 1: 'desert', 2: 'falador', 3: 'fremennik', 4: 'kandarin', 5: 'lumbridge', 6: 'morytania', 7: 'varrock', 8: 'western', 9: 'wilderness'}

Type in the number next to the diary: 6
option is valid
morytania_diary.txt 

----------------------------------------
Easy levels
----------------------------------------
{'Agility': 0,
 'Attack': 0,
 'Construction': 0,
 'Cooking': 0,
 'Crafting': 0,
 'Defense': 0,
 'Farming': 0,
 'Firemaking': 0,
 'Fishing': 0,
 'Fletching': 20,
 'Herblore': 0,
 'Hitpoints': 0,
 'Hunting': 9,
 'Magic': 0,
 'Mining': 15,
 'Prayer': 0,
 'Range': 30,
 'Runecrafting': 0,
 'Slayer': 0,
 'Smithing': 0,
 'Strength': 0,
 'Thieving': 0,
 'Woodcutting': 0}
----------------------------------------
Mediyum levels
----------------------------------------
{'Agility': 37,
 'Attack': 0,
 'Construction': 0,
 'Cooking': 42,
 'Crafting': 0,
 'Defense': 0,
 'Farming': 0,
 'Firemaking': 35,
 'Fishing': 46,
 'Fletching': 5,
 'Herblore': 0,
 'Hitpoints': 0,
 'Hunting': 31,
 'Magic': 0,
 'Mining': 40,
 'Prayer': 0,
 'Range': 30,
 'Runecrafting': 0,
 'Slayer': 0,
 'Smithing': 0,
 'Strength': 0,
 'Thieving': 0,
 'Woodcutting': 35}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38449484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档