首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在多个字符串上使用通配符或正则表达式

如何在多个字符串上使用通配符或正则表达式
EN

Stack Overflow用户
提问于 2019-06-19 03:58:31
回答 2查看 80关注 0票数 0

我有一个SKU名称列表,需要将缩写解析为单词。

缩写的长度不同(2-5个字符),但与实际单词的顺序一致。

下面是几个例子:

SKU名称:"235 DSKTP 10LB“-> "Desktop”

SKU名称:"222840 MSE 2 2oz“->”鼠标“

其他注释:

  1. SKU名称并不全是大写字母,尽管我知道使用.upper()方法可能更容易更改这一点,因为list of words I need to match is long (100+ words),所以创建一个匹配模式的单词列表可能是最有效的?

我尝试过一些正则表达式,但都没有用。

是否有类似于d? Is ?k?t?o?p的正则表达式模式?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-19 04:13:57

代码语言:javascript
复制
import re
from collections import OrderedDict

data = '''
235 DSKTP 10LB
222840 MSE 2oz
1234 WNE 1L
12345 XXX 23L
RND PTT GNCH 16 OZ 007349012845
FRN SHL CNCH 7.05 OZ 007473418910
TWST CLNT 16 OZ 00733544
'''

words = ['Desktop',
'Mouse',
'Tree',
'Wine',
'Gnocchi',
'Shells',
'Cellentani']

def compare(sku_abbr, full_word):
    s = ''.join(c for c in full_word if c not in set(sku_abbr) ^ set(full_word))
    s = ''.join(OrderedDict.fromkeys(s).keys())
    return s == sku_abbr

for full_sku in data.splitlines():
    if not full_sku:
        continue
    for sku_abbr in re.findall(r'([A-Z]{3,})', full_sku):
        should_break = False
        for w in words:
            if compare(sku_abbr.upper(), w.upper()):
                print(full_sku, w)
                should_break = True
                break
        if should_break:
            break
    else:
        print(full_sku, '* NOT FOUND *')

打印:

代码语言:javascript
复制
235 DSKTP 10LB Desktop
222840 MSE 2oz Mouse
1234 WNE 1L Wine
12345 XXX 23L * NOT FOUND *
RND PTT GNCH 16 OZ 007349012845 Gnocchi
FRN SHL CNCH 7.05 OZ 007473418910 Shells
TWST CLNT 16 OZ 00733544 Cellentani
票数 0
EN

Stack Overflow用户

发布于 2019-06-19 04:27:39

您可以创建一个将缩写与实际单词相关联的字典:

代码语言:javascript
复制
import re
names = ["235 DSKTP 10LB", "222840 MSE 2oz"]
abbrs = {'DSKTP':'Desktop', 'MSE':'Mouse'}
matched = [re.findall('(?<=\s)[a-zA-Z]+(?=\s)', i) for i in names]
result = ['N/A' if not i else abbrs.get(i[0], i[0]) for i in matched]

输出:

代码语言:javascript
复制
['Desktop', 'Mouse']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56656228

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档