Convert user alias to formal name in Python

I am trying to map users from different systems based on user name and user name in Python.

One problem is that the first names are in many cases nicknames. For example, for a user, his name is “Dave” in one system, and “David” in another.

Is there any easy way in python to convert regular aliases like these into their formal copies?

Thank!

+4
source share
3 answers

Not in Python, but try using this:

http://deron.meranda.us/data/nicknames.txt

python (csv.reader(<FileObject>, delimiter='\t')), , .

- :

import collections

def weighted_choice_sub(weights):
    # Source for this function:
    #  http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/
    rnd = random.random() * sum(weights)
    for i, w in enumerate(weights):
        rnd -= w
        if rnd < 0:
            return i

def load_names():
   with open(<filename>, 'r') as infile:
      outdict = collections.defaultdict(list)
      for line in infile.readlines():
          tmp = line.strip().split('\t')
          outdict[tmp[0]].append((tmp[1], float(tmp[2])))
   return outdict


def full_name(nickname):
    names = load_names()
    return names[nickname][weighted_choice_sub([x[1] for x in names[nickname]])][0]
+5

. , . , , , , , . , , , . .

0
In [1]: first_name_dict = {'David':['Dave']}
In [2]: def get_real_first_name(name):
   ...:     for first_name in first_name_dict:
   ...:         if first_name == name:
   ...:             return name
   ...:         elif name in first_name_dict[first_name]:
   ...:             return first_name
   ...:         else:
   ...:             return name
   ...:         

In [3]: get_real_first_name('David')
Out[3]: 'David'

In [4]: get_real_first_name('Dave')
Out[4]: 'David'

I am using Ipython. Basically you need a dictionary for this. First_name_dict - your dictionary with the first name. For example, David can be called "Dave" or "Davy", and Lucas can be called "Luke", then you can write a dictionary, for example:

first_name_dict = {'David' : ['Dave', 'Davy'], 'Lucas' : ['Luke']}

You can improve the solution by adding a case-insensitive match.

0
source

All Articles