我正在尝试根据 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]
关于python - 在Python中将用户昵称转换为正式名字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13615789/