我正在尝试根据Python中的用户名和姓来映射来自不同系统的用户.
一个问题是名字在很多情况下都是"昵称".例如,对于用户来说,他的名字在一个系统中是'Dave',在另一个系统中是'David'.
有没有简单的方法在python中将这些常见的昵称转换为正式的昵称?
谢谢!
不是特定于Python内部,但尝试使用此:
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]
Run Code Online (Sandbox Code Playgroud)