您可以使用os.path.commonprefix
來計算公共前綴。它用於計算文件路徑列表中的共享目錄,但可用於通用上下文中。
然後反轉字符串,並再次申請共同的前綴,然後反轉,來計算共同後綴(改編自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注意到:
- 當所有字符串相等時,常用前綴&後綴爲應該返回字符串本身而不是
prefix*suffix
:應檢查所有字符串是否相同
- 當通用前綴&後綴重疊/有共享字母時,這也會混淆計算:應該計算字符串上的公共後綴減去公共前綴
因此,需要一種全方位的方法來預先測試列表以確保至少有2個字符串不同(在過程中凝結前綴/後綴公式),並計算公共後綴切片以刪除常見前綴:
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
*
(當數據集爲空,代碼返回*
,也許這應該是另一種邊緣情況)
Dang,'os.path.commonprefix'!多久了。 – wim
upvote for commonprefix ...不知道它是否存在。 – Solaxun
相當不錯的一個,加上一個 –