2017-12-03 39 views
2

我想在字典中縮寫2個字符串中的第一個字。如何在python字典中創建縮寫

輸入字典:

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

我想這是輸出。

輸出詞典:

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

您所作的任何企圖? –

回答

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) 
0

通過使用joinsplit調整在字典中的值

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'} 
+0

@alecxe - 對,編輯 – Transhuman

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「。

雖然,我可以想象一個案例也可以打破這種方法。嚴格地說,這是一個自然語言處理問題,但取決於您的具體情況中可能的名稱。

+0

你試過了嗎?它不適用於兩個以上的名稱。 –

+0

@FranciscoCouzo啊,我們定義的「工作」不同:)我假定第一個字只能縮寫爲「工作」。但是,是的,在這種情況下如何表現可能取決於OP和這個問題的可能投入。謝謝。 – alecxe

0

這應該適用於您的字典中任何數量的單詞作爲值。

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