【问题标题】:How do I import text file dictionary into python dictionary如何将文本文件字典导入 python 字典
【发布时间】:2017-12-26 17:32:07
【问题描述】:

我正在创建一个锦标赛计分系统应用程序。 这个应用程序有很多部分,例如,参与者、团队、活动和奖励积分。 现在我在团队部分工作。我能够创建一些允许用户创建团队的东西。 代码如下所示。

teamname = input("Team Name: ").title()
First_member = input("First Member Full Name: ").title()
if any(i.isdigit() for i in First_member):
print("Invalid Entry")
else:

每个团队只能有 5 名成员。 这就是数据的保存方式

combine = '\''+teamname+'\' : \''+First_member+'\', \''+Second_member+'\', 
\''+Third_member+'\',  \''+Forth_member+'\',  \''+Fifth_member+'\'',                                  

myfile = open("teams.txt", "a+")
myfile.writelines(combine)
myfile.writelines('\n')
myfile.close()

现在如果我想移除一个团队,我该怎么做?

如果您觉得我在浪费您的时间,我们深表歉意,但仍然感谢您的光临。 如果您想查看所有内容,请查看此链接

https://repl.it/@DaxitMahendra/pythoncode>

【问题讨论】:

  • 你有代码吗?你试过什么?
  • 用户是手动输入数据还是通过文本文件输入数据?您的问题不清楚这部分
  • 请将您的代码添加到问题代码块中
  • @AriGold 我确实添加了

标签: python file dictionary external


【解决方案1】:

如果您可以创建文本文件,那么您应该拥有正确的 YAML 文件格式。您的格式与 YAML 非常相似。

拥有 YAML 后,您可以使用 PyYAML:https://pyyaml.org/wiki/PyYAMLDocumentation

这个答案:YAML parsing and Python? 有格式示例以及如何解析。

【讨论】:

  • 我是 python 新手,老实说不知道 YAML 是什么,但我会花时间研究一下。
【解决方案2】:

你必须做一个快速修复,请将你的“combine”变量格式更改为有效的“dict”格式,然后你可以使用“ast”模块,这里是一个例子

#proxy items
teamname,First_member,Second_member,Third_member,Forth_member,Fifth_member = [str(temp_name).zfill(3) for temp_name in range(6)]

#add "{" and "}" to start/end and add your values into a list "key":["value1", "value2",...]
combine = '{\''+teamname+'\' : [\''+First_member+'\', \''+Second_member+'\', \''+Third_member+'\',  \''+Forth_member+'\',  \''+Fifth_member+'\']}'

import ast
dict = ast.literal_eval(combine)
print dict.keys(), type(dict)
>>['000'] <type 'dict'>

对于你的情况,

#change the "combine" variable
combine = '{\''+teamname+'\' : [\''+First_member+'\', \''+Second_member+'\', \''+Third_member+'\',  \''+Forth_member+'\',  \''+Fifth_member+'\']}'

【讨论】:

  • 我已经添加了这些东西。打印了这个 dict_keys(['000']) 当我查看文件时有这个 {'000' : ['001', '002', '003', '004', '005 ']}
  • 这里添加这些数字,但添加代码后不添加成员的详细信息
  • 它只是一个例子,请根据您的情况更改它....有代理项目,删除该行
  • 老实说,伙计,我不知道我在做什么,你给我的例子对我来说毫无意义。已经1个月了。刚刚开始使用 python,这已经很糟糕了。我没想到我会通过这个 ******* 单元
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2020-08-26
相关资源
最近更新 更多