在python中查找字符串中的缩写

wag*_*lix 2 python

我们假设我们有一些可能的字符组合:

mystr = 'NRWTD'
my2str = RAWBC'
Run Code Online (Sandbox Code Playgroud)

现在我所知道的就是:

vdCacheType = {'AWB' : 'Always WriteBack', 'WB': 'Write Back',
               'NR': 'No Read Ahead', 'Ra': 'Read Ahead Adaptive',
               'WT': 'Write Through',  'R' : 'Read Ahead Always',
               'D': 'Direct IO', 'C': 'Cached' }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,字符串是缩写为Character/s的组合.我的问题是如何获取字符串,并检查字典组合是否可以在字典中找到.

我已经尝试过:

for x in vdCacheType:
    if x in mystr:
        print x # Here i would save the found abbr. in a list for later use
        mystr = mystr.strip(x)
Run Code Online (Sandbox Code Playgroud)

问题是对于NRWTD,它发现:

Found Char:  R
New String:  NRWTD
Found Char:  WT
New String:  NRWTD
Found Char:  NR
New String:  WTD
Found Char:  D
New String:  WT
Run Code Online (Sandbox Code Playgroud)

我的意图是回归:

没有预读,直写,直接

而不是NRWTD任何帮助是值得赞赏的,如果有更好的方法解决这个问题我是开放的.不管怎么说,还是要谢谢你!

Jon*_*nts 5

找到最长的子串:

vdCacheType = {'AWB' : 'Always WriteBack', 'WB': 'Write Back',
               'NR': 'No Read Ahead', 'Ra': 'Read Ahead Adaptive',
               'WT': 'Write Through',  'R' : 'Read Ahead Always',
               'D': 'Direct IO', 'C': 'Cached' }

import re
rx = re.compile('|'.join(sorted(vdCacheType, key=len, reverse=True)))
print ', '.join([vdCacheType[m] for m in rx.findall('NRWTD')])
# No Read Ahead, Write Through, Direct IO
Run Code Online (Sandbox Code Playgroud)

RAWBC出来:Read Ahead Always, Always WriteBack, Cached

根据区分大小写进行调整以及整个文本是否应该是一个完整的首字母缩略词(或系列).