python - 从文本字典中访问值
问题描述
我正在尝试创建一个“这是您的新名称生成器”程序。我通过询问用户他们的名字和姓氏来做到这一点。然后程序获取他们名字的第一个字母和他们姓氏的最后一个字母,并从两个文本文件中提取他们的新名字和姓氏。
我已经获得了用户的名字和姓氏,并从文件中提取信息,但是它总是给我文件的最后一行。
我以为我可以像字典一样设置文件,然后将用户的输入用作键,但它似乎不起作用。
有什么建议吗?
firstName = input("What is your first Name? ")
lastName = input("What is your last Name? ")
fN = firstName[0].lower()
lN_len = len(lastName) -1
lN = lastName[lN_len]
fNdict = {}
with open('firstName.txt') as f:
for line in f:
(fN, fNval) = line.split(",")
fNdict[fN] = fNval
lNdict = {}
with open('lastName.txt') as fileobj:
for line in fileobj:
lNkey, lNvalue = line.split(",")
lNdict[lN] = lNvalue
newFirstName = fNval
newLastName = lNvalue
print("Your zombie Name is: %s %s "%(newFirstName,newLastName))
参考图片:
解决方案
您可以遵循稍微不同的实现来获得相同的结果。
- 创建两个具有所有关联字母的 python 字典 - 名字和字母 - 姓氏。
- 使用json将它们写入文件中。此文件将替换您的 firstName.txt 和 lastName.txt
这应该只执行一次以创建具有名称的文件。
然后你的名字生成器是一个脚本,它:
- 加载这两个字典。
- 要求用户输入以获取密钥。
- 使用用户输入从字典中检索名称。
前两点是这样实现的:
import json
#these are just brief examples, provide complete dictionaries.
firstnames = {"A": "Crafty", "B": "Brainy"}
lastnames = {"A": "Decapitator", "B": "McBrains"}
with open("fullnames.txt", "w") as ff:
json.dump(firstnames, ff)
ff.write('\n')
json.dump(lastnames, ff)
这将是一个脚本,用于生成具有名称的文件。
名称生成器将是:
import json
with open("fullnames.txt", "r") as ff:
ll = ff.readlines()
firstnames = json.loads(ll[0].strip())
lastnames = json.loads(ll[1].strip())
inputfirst = input("What is your first Name? ")
inputlast = input("What is your last Name? ")
fn = inputfirst[0].upper()
ln = inputlast[-1].upper() #negative indexes start from the last element of the iterable, so -1 would be the last.
print("Your zombie Name is: {} {} ".format(firstnames[fn], lastnames[ln])) #using string format method, better that the old %
推荐阅读
- python - AttributeError:“str”对象没有属性“name”PySpark
- java - 使用 Java 流从 int 数组中获取缺失的数字
- css - 随屏幕尺寸变化堆叠元素的困难
- css - 如何防止表单自动填充软件/浏览器扩展(例如 Dashlane)干扰 HTML 元素的样式?
- c# - C# Linq Query 比较两个表
- django - 我在 Heroku 中设置了时区,但没有任何变化
- python - 使用Python单击Selenium按钮
- java - 选择一个随机索引,然后从该索引中获取属性(Jmeter)
- deep-learning - 训练时每个通道预期超过 1 个值,得到输入大小 torch.Size([1, xx])
- hybrid-mobile-app - How to design a multi platform video conference/chat app?