假设这两组字符串:
file=sheet-2016-12-08.xlsx
file=sheet-2016-11-21.xlsx
file=sheet-2016-11-12.xlsx
file=sheet-2016-11-08.xlsx
file=sheet-2016-10-22.xlsx
file=sheet-2016-09-29.xlsx
file=sheet-2016-09-05.xlsx
file=sheet-2016-09-04.xlsx
size=1024KB
size=22KB
size=980KB
size=15019KB
size=202KB
我需要分别在这两个集合上运行一个函数并分别接收以下输出:
file=sheet-2016-*.xlsx
size=*KB
数据集可以是任意一组字符串。它不必与格式匹配。这是另一个例子:
id.4030.paid
id.1280.paid
id.88.paid
预期的输出是:
id.*.paid
基本上,我需要一个函数来分析一组字符串并用星号 (*) 替换不常见的子字符串
最佳答案
您可以使用 os.path.commonprefix
来计算公共(public)前缀。它用于计算文件路径列表中的共享目录,但它可以在通用上下文中使用。
然后反转字符串,再次应用公共(public)前缀,然后反转,计算公共(public)后缀(改编自 https://gist.github.com/willwest/ca5d050fdf15232a9e67 )
dataset = """id.4030.paid
id.1280.paid
id.88.paid""".splitlines()
import os
# Return the longest common suffix in a list of strings
def longest_common_suffix(list_of_strings):
reversed_strings = [s[::-1] for s in list_of_strings]
return os.path.commonprefix(reversed_strings)[::-1]
common_prefix = os.path.commonprefix(dataset)
common_suffix = longest_common_suffix(dataset)
print("{}*{}".format(common_prefix,common_suffix))
结果:
id.*.paid
编辑:如 wim 所述:
- 当所有字符串相等时,公共(public)前缀和后缀相同,但它应该返回字符串本身而不是
prefix*suffix
:应该检查所有字符串是否相同 - 当公共(public)前缀和后缀重叠/共享字母时,这也会混淆计算:应该计算字符串上的公共(public)后缀减去公共(public)前缀
因此需要一个一体化的方法来预先测试列表以确保至少有 2 个字符串是不同的(在此过程中压缩前缀/后缀公式),并通过切片计算公共(public)后缀以删除公共(public)前缀:
def compute_generic_string(dataset):
# edge case where all strings are the same
if len(set(dataset))==1:
return dataset[0]
commonprefix = os.path.commonprefix(dataset)
return "{}*{}".format(commonprefix,os.path.commonprefix([s[len(commonprefix):][::-1] for s in dataset])[::-1])
现在让我们测试一下:
for dataset in [['id.4030.paid','id.1280.paid','id.88.paid'],['aBBc', 'aBc'],[]]:
print(compute_generic_string(dataset))
结果:
id.*.paid
aB*c
*
(当数据集为空时,代码返回*
,也许这应该是另一种边缘情况)
关于python - 在字符串列表中标记动态子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45890136/