当前位置:首页 » Python技术

python 计算子字符串的数量

2018-08-22 14:24 本站整理 浏览(63)

#coding=utf-8
def countSubStr(str1):
  dict1 = {}
  list1 = []
 
  s_len = len(str1) + 1
  if s_len<2:
    return dict;
 
  for i in range(0,s_len):
    for j in range(i+2,s_len):
      list1.append(str1[i:j])
 
  for s in list1:
    # print('%s-%s' % (s,list1.count(s)))
    dict1.setdefault(s,list1.count(s)) # 去重
  return dict1
res = countSubStr('abcabcd')
print(res)
res = countSubStr('abc')
print(res)
结果:
{'ab': 2, 'abc': 2, 'abca': 1, 'abcab': 1, 'abcabc': 1, 'abcabcd': 1, 'bc': 2, 'bca': 1, 'bcab': 1, 'bcabc': 1, 'bcabcd': 1, 'ca': 1, 'cab': 1, 'cabc': 1, 'cabcd': 1, 'abcd': 1, 'bcd': 1, 'cd': 1}
{'ab': 1, 'abc': 1, 'bc': 1}
另一版:
#coding=utf-8
sString = 'abcabcd'
len = len(sString)
list = []
list1 = []
i = 0
if len <= 1 :
    print("")
else:
    while (i <= len):
        j = i+2
        while (j <= len):
            list.append(sString[i:j])
            if sString[i:j] not in list1:
                list1.append(sString[i:j])
            j += 1
        i += 1
print (list1)
for k in list1:
    print(k,list.count(k))