如何在python词典中创建缩写

时间:2017-12-03 04:46:10

标签: python dictionary

我想在字典中缩写2个单词字符串中的第一个单词。

输入字典:

names = {
    'fire' : 'John Smith', 'water' : 'Steve Doe', 'earth' : 'Bob Smith'
}

我希望这是输出。

输出字典:

names_ab = {
    'fire' : 'J. Smith', 'water' : 'S. Doe', 'earth' : 'B. Smith'
}

4 个答案:

答案 0 :(得分:0)

你可以这样做:

names = {'fire': 'John Smith', 'water': 'Steve Doe', 'earth': 'Bob Smith'}

names_ab = {}
for element, name in names.items():
    first_name, last_name = name.split()
    names_ab[element] = '{}. {}'.format(first_name[0], last_name)

print(names_ab)

哪个输出:

{'fire': 'J. Smith', 'water': 'S. Doe', 'earth': 'B. Smith'}

如果您需要它来使用更多名称,您可以使用以下内容:

for element, name in names.items():
    *first_names, last_name = name.split()
    names_ab[element] = '{}. {}'.format('. '.join(n[0] for n in first_names), last_name)

答案 1 :(得分:0)

使用joinsplit

调整dict中的值
names = { 'fire' : 'John Smith', 'water' : 'Steve Doe', 'earth' : 'Bob Smith will' }
{k:'. '.join([v[0],' '.join(v.split()[1:])]) for k,v in names.items()}
#Output:
#{'earth': 'B. Smith will', 'fire': 'J. Smith', 'water': 'S. Doe'}

答案 2 :(得分:0)

一种可能的方法是在捕获组中提取第一个大写字母,并使用re.sub()在替换字符串中引用捕获的组:

In [1]: import re

In [2]: names = { 'fire' : 'John Smith', 'water' : 'Steve Doe', 'earth' : 'Bob Smith' }

In [3]: pattern = re.compile(r"^([A-Z])[a-z]+")

In [4]: print({key: pattern.sub(r"\1.", value)
   ...:        for key, value in names.items()})
{'fire': 'J. Smith', 'water': 'S. Doe', 'earth': 'B. Smith'}

请注意,这也可以处理字符串中定义的单词/名称数超过两个的情况 - 例如" Amy Farrah Fowler"。

虽然,我可以设想一个案例来打破这种方法。严格来说,这是一个自然语言处理问题,但也取决于你的特定情况下可能的名称是什么。

答案 3 :(得分:0)

这应该适用于你的dict中任意数量的单词作为值。

names = {'earth': 'Bob Smith Jobs', 'fire': 'John Smith', 'water': 'Steve Doe'}

d = {}

for k in names:
    first, *rest = names[k].split()
    d[k] = '{0}. '.format(first[0]) + ' '.join(rest)

print(d)

但这仅适用于Python 3