从名字和姓氏中提取首字母,并将其与单独的词典进行比较

2024-04-26 04:53:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,需要一些帮助。你知道吗

我要做的是,从用户输入的名字和姓氏中提取首字母。然后我想把这些首字母和外部文件中的一些数据进行比较。我以读取模式打开文件并将数据导入字典。你知道吗

dict1 = {'EV': ' Erik Vils', 'EVI': ' Erik Vils', 'EVIL': ' Erik Vils', 'RH': ' Rasmus Holst', 'RHO': ' Rasmus Holst', 'KA': ' Kasper Andersen'}

firstname = input('write firstname')
surname = input('write surname')

mylist=[]
mylist.append(firstname)
mylist.append(surname)

myinitals = ''.join([x[0] for x in mylist]) 
mylist=[firstname + ' ' + surname] 
mylist.append (myinitals) 

a1=mylist[0] 
b1=mylist[1] 

dict2 = {}
for item in mylist:
    x = line.split(",")
    a1 = a1.strip('') 
    b1 = b1.strip('') 
    dict2[b1]=a1 
>>> dict2 ={'EV': 'Erik Vils'}

从这里我被困住了。我想生成不等于dict1中任何键的初始值,在本例中,结果='Evils':'Erik Vils'。 我试着做了一段时间的循环:

aux = dict1.keys()
while b1 in aux:
    b1=b1+surname[1:aux]

但这行不通,你们有谁知道解决办法吗?你知道吗


Tags: 文件数据ina1surnamefirstnameb1append
2条回答

你说得对,我已经基于用户列表编写了一个类似的实现。您可以根据用户输入将其更改为附加到列表:

from collections import OrderedDict

names = ['Erik Vils', 'Erik Vils', 'Erik Vils', 'Erik Vils', 'Erik Vils', 'Somebody Else', 'Peter Pan', 'Peter Pan']

all_users = OrderedDict()

for entry in names:
    firstname, lastname = entry.split()
    i = 1
    while True:
        add_number=""
        if i >= len(lastname):
            add_number = i - len(lastname)
        username = firstname[0] + lastname[:i] + str(add_number)
        username = username.upper()
        if username not in all_users:
            all_users[username] = entry
            break
        i += 1

print(all_users)

# prints OrderedDict([('EV', 'Erik Vils'), ('EVI', 'Erik Vils'), ('EVIL', 'Erik Vils'), ('EVILS', 'Erik Vils'), ('EVILS1', 'Erik Vils'), ('SE', 'Somebody Else'), ('PP', 'Peter Pan'), ('PPA', 'Peter Pan')])

我还使用了orderedict来保留名字插入的顺序。然而,这是没有必要的。你知道吗

下面是另一个解决方案:

dict1 = {'EV': ' Erik Vils', 'EVI': ' Erik Vils', 'EVIL': ' Erik Vils', 'RH': ' Rasmus Holst', 'RHO': ' Rasmus Holst', 'KA': ' Kasper Andersen'}

firstname = input('write firstname')
surname = input('write surname')

myinitals = firstname[0] + surname[0]

counter = 1

while myinitals in dict1:
    myinitals = firstname[0] + surname[0:counter]
    counter += 1

print(myinitals)

这并不像罗伯茨的回答那样防弹,但更容易理解(希望如此)。你知道吗

相关问题 更多 >