1. 程式人生 > >4-1如何拆分含有多個分隔符的字符串

4-1如何拆分含有多個分隔符的字符串

white sep 則表達式 src OS esp style readlines rds

技術分享圖片

1、介紹str.split()用法

上一篇《python調用shell命令》介紹了如何用python調用系統命令。

(1)列出windows進程列表

>>> import os
>>> tmp = os.popen(‘tasklist‘).readlines()
>>> tmp

(2)取出切片,顯示最後一行

>>> s = tmp[-1]
>>> s

‘tasklist.exe 6524 Console 1 5,740 K\n‘

(3)將字符串拆分

Str.split()用法

技術分享圖片
>>> help(s.split)
Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings
    
    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
from the result.
help(s.split)

如果以空白分隔符(\t、\r、\n空格等)為拆分時分隔符參數可以不傳或傳入None。

>>> s.split()

[‘tasklist.exe‘, ‘6524‘, ‘Console‘, ‘1‘, ‘5,740‘, ‘K‘]

2、采用多次str.split()方法

>>> s = ab;cd|df,oi.kjqw;soic\sf
>>> def mysplit(s,ds):
    res = [s]            #將字符串s轉為列表,列表包含一個大的字符串
    for d in ds:
        t 
= [] map(lambda x : t.extend(x.split(d)) , res) #將每次從res分割的字符串添加到列表t中 res = t #再把列表t賦值給res,做為下次叠代時使用,新的分割後的列表 return [x for x in res if x] #將字符串過濾,防止有兩個相近的分割符導致,出出None空字符串。 >>> mysplit(s,";|,.\\")

[‘ab‘, ‘cd‘, ‘df‘, ‘oi‘, ‘kjqw‘, ‘soic‘, ‘sf‘]

Map()函數在《2-5查找字典公共鍵》中有過介紹,map()函數接收兩個參數,一個是函數,一個是Iterablemap將傳入的函數依次作用到序列的每個元素,並把結果作為新的Iterator返回。此例中,lambda的參數x即為res列表的每一個元素(只有一個元素是一個大列表)。

列表的extend在《2-1 如何在列表字典集合中根據條件篩選數據》中有過舉例,這個函數是將添加的函數不管是什麽,都轉為一元列表。Lambda用法也在這裏有過介紹。

mysplit()函數推導過程

>>> s
ab;cd|df,oi.kjqw;soic\\sf
>>> s1 = s.split(;)
>>> s1

[‘ab‘, ‘cd|df,oi.kjqw‘, ‘soic\\sf‘]

s.split()分割後的字符串組成了列表,s1是列表沒有split()函數,此時要對s1列表中各個元素再進行分割,可以用map()函數,因為他是將某個功能作用在可叠代對象的各個元素上的,正好,每個元素實際上是一個字符串。

>>> new = map(lambda x : x.split(|),s1)
>>> new

[[‘ab‘], [‘cd‘, ‘df,oi.kjqw‘], [‘soic\\sf‘]]

執行兩次後,new變成了一個二維列表,列表中還有列表,所以用到了,空列表,進行extend()轉化為一維列表的思想。

3、使用re.split()方法

>>> import re
>>> re.split(r[;|,.\\]+,s)

[‘ab‘, ‘cd‘, ‘df‘, ‘oi‘, ‘kjqw‘, ‘soic‘, ‘sf‘]

技術分享圖片
>>> help(re.split)
Help on function split in module re:

split(pattern, string, maxsplit=0, flags=0)
    Split the source string by the occurrences of the pattern,
    returning a list containing the resulting substrings.
help(re.split)

正則表達式在《2-3統計序列元素出現的頻度》中有過介紹,re.split()函數的第一個參數為“正則表達式的規則”,本例中,[;|,.\\]為方括號中的元素中的任意一個。後面的+號表式有1或無限多個。

4-1如何拆分含有多個分隔符的字符串