【问题标题】:Get the suffix from a list of similar string从相似字符串列表中获取后缀
【发布时间】:2020-06-23 06:19:42
【问题描述】:
# code to get commonprefix
    def commonprefix(m):
        if not m: return ''
        s1 = min(m)
        s2 = max(m)
        for i, c in enumerate(s1):
            if c != s2[i]:
                return s1[:i]
        return s1
#code to get the different suffix 
    strList = map(str, objList)
    strList = map(lambda x: x.replace('', ''), strList)  

# My code to get the different suffix of each element of a list 

    for i in range(len(liste)):

        Listelement = liste[i]["title"].tolist()
        common_name = commonprefix(Listelement)
        try:
            strList = map(str, Listelement) 
            strList = map(lambda x: x.replace(common_name, ''), strList)
            print(Listelement)
        except:
            pass

# this is how my "Listelement" variable look like

    ['Le Coton Coton Extra Doux Boîte 100pce - CHANEL']
    ['Allure Eau De Toilette Vaporisateur 50ml - CHANEL', 'Allure Eau De Toilette Vaporisateur 100ml - CHANEL']
    ['Allure Eau De Toilette Vaporisateur 50ml - CHANEL', 'Allure Eau De Toilette Vaporisateur 100ml - CHANEL']
    ['Eau De Cologne Les Exclusifs De Chanel 75ml - CHANEL', 'Eau De Cologne Les Exclusifs De Chanel 200ml - CHANEL']
    ['Eau De Cologne Les Exclusifs De Chanel 75ml - CHANEL', 'Eau De Cologne Les Exclusifs De Chanel 200ml - CHANEL']

大家好,我在查找产品列表的后缀时遇到了一个小问题。我得到了公共前缀函数,它为我的列表提供了正确的答案,但是当我尝试删除每个列表中每个元素的 common_prefix 时,它不起作用,你知道为什么吗? 非常感谢你

【问题讨论】:

  • 你能做一个最小可复制的例子吗?这里我们不知道如何使用你的数据,liste 也不是
  • 能否请您明确举例说明您对“通用前缀”和“通用后缀”的定义?尤其是后缀,应该是ml - CHANEL还是CHANEL?
  • 例如第二个列表,后缀为 ['50ml - CHANEL', '100ml - CHANEL'] 我只是想删除类似的部分

标签: python prefix suffix


【解决方案1】:
  1. 您无需为os.path.commonprefix 重新发明轮子。
  2. 此外,您可以对字符串使用slicing 语法,而不是逐个计算字符。

解决方案

import re
import os

ls = ['Allure Eau De Toilette Vaporisateur 50ml - CHANEL', 'Allure Eau De Toilette Vaporisateur 100ml - CHANEL']

# find common prefix
pfx = os.path.commonprefix(ls)
ans = [el[len(pfx):] for el in ls]
print(ans)  # ['50ml - CHANEL', '100ml - CHANEL']

【讨论】:

    猜你喜欢
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    相关资源
    最近更新 更多