如何根据字典对字符串进行分类?

2024-10-01 07:46:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的口述如下:

strdirList = {'W':['WEST', 'WES', 'WE'], 'E': ['EAST', 'EA'], 'N':'NORTH', 
              'S':'SOUTH'}

根据这句话,如果我有一个字符串,比如:

direction1 = 'WES EXAMPLE NORTH'
direction2 = 'EXAMPLE NORTH WES'

我想得到的回报是

nameString1 = 'EXAMPLE NORTH'
direction1 = 'W'
nameString2 = 'EXAMPLE WES'
direction2 = 'N' 

我目前的代码如下:

for e in range(len(directionList)):
    word = list(strdirList.keys())
    for i in range(len(word)):
        for n in range(len(strdirList[word[i]])):
            if directionList[e] == strdirList[word[i]][n]:
                directionList[e] = \
                directionList[e].replace(strdirList[word[i]][n], word[i])

我目前的代码是不正常的,不工作,有没有更好的和优雅的方式来解决这个问题?非常感谢!你知道吗

更新: 我只想更改第一个需要更改的元素,并记录它的类,我该怎么办?你知道吗

更新2: 我试着自己解决,但不只是修改第一个,代码如下:

for i in range(len(directionList)):
    for sdic in strdirList.keys():
        if directionList[i] in strdirList[sdic]:
            directionList[i] = sdic
            break
for item in directionList:
    if item in strdirList.keys():
        directionList.remove(item)
        direction = item
        break
else:
    direction = ''

更新3: 我目前有一个解决问题的方法,如下所示,但它只适用于平底词典:

def test(strdirList, direction):
    directionList = direction.split(' ')
    for i in range(len(directionList)):
        for sdic in strdirList.keys():
            if directionList[i] in strdirList[sdic]:
                directionList[i] = sdic
                return directionList
directionList = test(strdirList, direction)
for item in directionList:
    if item in strdirList.keys():
        directionList.remove(item)
        direction = item
        break
else:
    direction = ''

现在对我来说确实有效,但是如果有人有更好的优雅方式,请把你的答案写在这里!你知道吗


Tags: inforlenifexamplerangekeysitem
1条回答
网友
1楼 · 发布于 2024-10-01 07:46:22

您可以使用re.sub

import re
strdirList = {'W':['WEST', 'WES', 'WE'], 'E': ['EAST', 'EA'], 'N':'NORTH', 
          'S':'SOUTH'}

direction = 'WES EXAMPLE NORTH'
new_direction = re.sub('\w+', lambda x:(lambda c:x.group() if not c else c[0])([a for a, b in strdirList.items() if x.group() in b]), direction)

输出:

'W EXAMPLE N'

编辑:

def get_direction(direction):
   flag = False
   for i in direction.split():
     if any(i in c for c in strdirList.values()) and not flag:
       yield [a for a, b in strdirList.items() if i in b][0]
       flag = True
     else:
       yield i

direction = ['WES EXAMPLE NORTH', 'EXAMPLE WES NORTH', 'EXAMPLE NORTH WES']
print(list(map(lambda x:' '.join(get_direction(x)), direction)))

输出:

['W EXAMPLE NORTH', 'EXAMPLE W NORTH', 'EXAMPLE N WES']

相关问题 更多 >