2013-01-16 44 views
0

我期望实现的是以特定模式在列表中排列项目。我说,我有以下的解释:按特定模式排列列表项

>>>dict_a = { 
     'north' : 'N', 
     'south' : 'S', 
     'east' : 'E', 
     'west' : 'W', 
     'north east' : 'NE', 
     'north west' : 'NW' 
    } 

我们检查,如果一个字符串包含从上述词典中的任何项目我做的:

>>>string_a = 'North East Asia' 
>>>list_a = [] 
>>>for item in dict_a: 
     if item in string_a.lower(): 
      list_a.append(item) 

,它给我的结果如下,这是有道理的

>>>['north', 'north east', 'east'] 

但我希望得到的是['north east']而忽略northeast。我如何实现这个目标?

+0

检查的前两个单词'string_a'建立在字典 – gefei

+0

单独的字典的关键一分为二,并与各一通。 – StoryTeller

回答

5

尝试difflib.closest_match

>>> dict_a = { 
     'north' : 'N', 
     'south' : 'S', 
     'east' : 'E', 
     'west' : 'W', 
     'north east' : 'NE', 
     'north west' : 'NW' 
    } 
>>> import difflib 
>>> string_a = 'North East Asia' 
>>> dict_a[difflib.get_close_matches(string_a, dict_a.keys())[0]] 
'NE' 
2
>>> max(['north', 'north east', 'east'], key=len) 
'north east' 
3

你可以(在Python 2.7+新),其存储在一个一致的顺序键/值对使用OrderedDict。为了获得单个结果,只需在第一场比赛后打破循环。

import collections 

# create the mapping with the desired order of matches 
dict_a = collections.OrderedDict([ 
    ('north east', 'NE'), 
    ('north west', 'NW'), 
    ('north', 'N'), 
    ('south', 'S'), 
    ('east', 'E'), 
    ('west', 'W'), 
]) 

string_a = 'North East Asia' 
list_a = [] 
for item in dict_a: 
    if item in string_a.lower(): 
     list_a.append(item) 
     break # found something