LZW 算法用于查找输入符号之间的模式。但它能在词中寻找模式吗?我的意思是 alfabet 索引不是符号,而是例如输入的单词:
'abcd', 'abcd', 'fasf' , 'asda', 'abcd' , 'fasf' ...
有一个像这样的输出:
'abcd', '1', 'fasf' , 'asda' , '1', '2' ...
或者是否有任何压缩算法可以解决问题?
LZW 算法用于查找输入符号之间的模式。但它能在词中寻找模式吗?我的意思是 alfabet 索引不是符号,而是例如输入的单词:
'abcd', 'abcd', 'fasf' , 'asda', 'abcd' , 'fasf' ...
有一个像这样的输出:
'abcd', '1', 'fasf' , 'asda' , '1', '2' ...
或者是否有任何压缩算法可以解决问题?
keys = []
def lzw(text):
tokens = text.split()
new_keys = dict.fromkeys(tokens).keys()
keys.extend([key for key in new_keys if key not in keys])
encoded = ["%s"%keys.index(tok) for tok in tokens]
for i,key in enumerate(keys):
try:
encoded[encoded.index(str(i))] = key
except:
pass
return " ".join(encoded)
print lzw("abcd abcd fasf asda abcd fasf")
#outputs: abcd 0 fasf asda 0 2
是一个非常简单的实现
您可以使用此代码搜索字符串以查找模式。不过,您将需要知道要搜索的模式。
## Search for pattern 'iii' in string 'piiig'.
## All of the pattern must match, but it may appear anywhere.
## On success, match.group() is matched text.
match = re.search(r'iii', 'piiig') => found, match.group() == "iii"
match = re.search(r'igs', 'piiig') => not found, match == None
阅读本网站: https ://developers.google.com/edu/python/regular-expressions?hl=iw