从文本文件创建用户名

时间:2014-11-26 21:33:01

标签: python list python-3.x count

我只知道我对此很不满意,所以请耐心等待。到目前为止我已经尽力了!

从具有前导名和姓氏(一些具有中间名)的文本文件中读取行,以生成用户名,该用户名是forename和任何中间名的连接版本。如果有重复,我们从他们的姓氏中输入第一个字母。如果仍然重复,我们后缀为1,并从那里开始计数以获得更多重复项 - 我只是无法让这部分工作!

usernames = []

for line in open('classlist.txt'):
  count = 0
  name = line.lower().split()
  surname = name[-1]
  username = ''.join(name[0:-1])
  username_w_surname = username + surname[0]
  username_w_surname_integer = username_w_surname + str(count)
  if username not in usernames:
    usernames.append(username)
  elif username in usernames:
    usernames.append(username_w_surname)
  elif username_w_surname in usernames:
    count = count + 1
    usernames.append(username_w_surname_integer)

for entry in usernames:
  print (entry)

返回

max
katherine
annamarie
james
jamesp
jamesp
jamesb

但第二个jamesp应为jamesp1

2 个答案:

答案 0 :(得分:1)

你的前两个条款:

if username not in usernames:
    usernames.append(username)
elif username in usernames:
    usernames.append(username_w_surname)

涵盖所有可能性,因为用户名是用户名,或者不是。因此,您永远不会进入第三个区块:

elif username_w_surname in usernames:
    count = count + 1
    usernames.append(username_w_surname_integer)

这应该可以解决问题:

  if username not in usernames:
    usernames.append(username)
  elif username_w_surname not in usernames:
    usernames.append(username_w_surname)
  else:
    count = count + 1
    usernames.append(username_w_surname_integer)

最后的优化提示:不是使用列表来收集用户名,而是查看sets

答案 1 :(得分:0)

你也可以尝试这个

usernames = []
for line in open('classlist.txt'):
  count = 1
  name = line.lower().split()
  surname = name[-1]
  username = ''.join(name[0:-1])
  username_w_surname = username + surname[0]
  username_w_surname_integer = username_w_surname + str(count)
  if username not in usernames:
        usernames.append(username)
  elif username in usernames:            
        if username_w_surname in usernames:
                    count = count + 1
                    usernames.append(username_w_surname_integer)
        else:
            usernames.append(username_w_surname)
for entry in usernames:
  print (entry)