今天实在没啥事干,用Python写了个splitstr函数,就是将内置函数优化了一下...
添加了splitmode、remove_empty_char、sortword、setword这四个功能
直接上代码!!!
def splitstr(masterstr,substr=' ',amount=-1,splitmode=None,rm_empty_char=True,sortword=False,setword=False):
if masterstr[-1] != substr:
masterstr += substr # 判断最后一位是否为substr,如果不是将masterstr添加substr,以截取最后一个nowsplitword
split_list = []
last_search_pos = 0
num = 0 if amount != -1 else -1 # 判断num的值,如果amount是-1的话(即截取全部)不用设置
substr_pos = masterstr.find(substr,last_search_pos)
while substr_pos != -1 and (num < amount if num != -1 else True):
nowsplitword = masterstr[last_search_pos:last_search_pos+substr_pos-last_search_pos]
last_search_pos = substr_pos+len(substr)
substr_pos = masterstr.find(substr,last_search_pos)
if num != -1:
num += 1 # 判断num的值,如果amount是-1的话(即截取全部)不用自加
if rm_empty_char and nowsplitword == '': # 判断nowsplitword是否为空(即判断两个及以上的substr在一起会产生空格的情况),如果是:continue
continue
if splitmode == None: # splitmode分为None、Title、Lower、Upper
split_list.append(nowsplitword)
elif splitmode == 't':
split_list.append(nowsplitword.title())
elif splitmode == 'l':
split_list.append(nowsplitword.lower())
elif splitmode == 'u':
split_list.append(nowsplitword.upper())
if num != -1:
surplus = masterstr[last_search_pos:-1]
split_list.append(surplus)
if setword == True:
split_list = list(set(split_list))
if sortword == True:
split_list.sort()
return split_list
调用这个函数:
str1 = "Hello Python World ! Life is short , I use Python !" str2 = "Hello_Python_World_!_Life_is_short_,_I_use_Python_!" str3 = "Hello!Python!World!!Life!is!short!,!!I use Python!!" print(splitstr(str1)) # ['Hello', 'Python', 'World', '!', 'Life', 'is', 'short', ',', 'I', 'use', 'Python', '!'] print(splitstr(str2,'_')) # ['Hello', 'Python', 'World', '!', 'Life', 'is', 'short', ',', 'I', 'use', 'Python', '!'] print(splitstr(str1,amount=6)) # ['Hello', 'Python', 'World', '!', 'Life', 'is', 'short , I use Python !'] print(splitstr(str1,splitmode='t')) print(splitstr(str1,splitmode='l')) print(splitstr(str1,splitmode='u')) # ['Hello', 'Python', 'World', '!', 'Life', 'Is', 'Short', ',', 'I', 'Use', 'Python', '!'] # ['hello', 'python', 'world', '!', 'life', 'is', 'short', ',', 'i', 'use', 'python', '!'] # ['HELLO', 'PYTHON', 'WORLD', '!', 'LIFE', 'IS', 'SHORT', ',', 'I', 'USE', 'PYTHON', '!'] print(splitstr(str3,'!',rm_empty_char=False)) # ['Hello', 'Python', 'World', '', 'Life', 'is', 'short', ',', '', 'I use Python', ''] print(splitstr(str1,sortword=True)) # ['!', '!', ',', 'Hello', 'I', 'Life', 'Python', 'Python', 'World', 'is', 'short', 'use'] print(splitstr(str1,setword=True)) # ['World', 'Python', 'I', 'is', 'use', 'short', ',', 'Hello', 'Life', '!']
代码效果就是这样啦,如果有改进的地方请私信给我,不喜欢勿喷...
代码下载链接:PythonPyFOL之Split函数(Python内置Split函数优化升级版)-数据集文档类资源-CSDN下载



