首页 > 解决方案 > 从文本字典中访问值

问题描述

我正在尝试创建一个“这是您的新名称生成器”程序。我通过询问用户他们的名字和姓氏来做到这一点。然后程序获取他们名字的第一个字母和他们姓氏的最后一个字母,并从两个文本文件中提取他们的新名字和姓氏。

我已经获得了用户的名字和姓氏,并从文件中提取信息,但是它总是给我文件的最后一行。

我以为我可以像字典一样设置文件,然后将用户的输入用作键,但它似乎不起作用。

有什么建议吗?

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

解决方案


您可以遵循稍微不同的实现来获得相同的结果。

  1. 创建两个具有所有关联字母的 python 字典 - 名字和字母 - 姓氏。
  2. 使用json将它们写入文件中。此文件将替换您的 firstName.txt 和 lastName.txt

这应该只执行一次以创建具有名称的文件。

然后你的名字生成器是一个脚本,它:

  1. 加载这两个字典。
  2. 要求用户输入以获取密钥。
  3. 使用用户输入从字典中检索名称。

前两点是这样实现的:

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 %

推荐阅读