关于Python中split函数那些事

关于Python中split函数那些事

 

前言

在学习决策树算法中需要将文本的数据提取出来,看到如下格式的文本想到的就是split函数:

sunny      hot             high           false       N

sunny      hot             high           true         N

overcast  hot             high           false       P

rain           mild           high           false       P


由于数据记录比较长,把每列之间的空格统一需要耗一定的时间,想到split函数利用空格分隔字符串,取第一行做测试,代码如下:

这肯定不是我想要的结果,首先想到的是不是这个函数用错了,就help(str.split):

String.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 isgiven, 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.


大致意思是利用Sep 分隔字符串,返回分隔后的列表;如果指定maxsplit则最多返回的列表长度不大于maxsplit,即分割多少次的意思例如:

>>> u = "www.doiido.com.cn"

#分割一次

>>>print u.split('.',1)

['www','doiido.com.cn']

#分割两次

>>>print u.split('.',2)

['www','doiido', 'com.cn']


最后发现这个函数根本不能一次性分隔出我想要的列表,只能问问百度大哥,终于发现python提供split函数,不是string特有的,还有个比较重要的模块也有,就是正则表达式re模块。

re.split函数

用这个函数之前,需加载re模块:

Import re

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 listcontaining the resulting substrings.


这函数有一个主要的参数pattern,译为模式,也就是会按照你给定的模式分割字符串(模式有什么规则,请搜索正则表达式,这里不累述)还用上面的例子:

<strong>re.split('\s+',str)

['sunny', 'hot', 'high', 'false', 'N']</strong>


OK,得到正确的结果。

 

在网上还发现,还有个split函数用的比较多,就是路径分割

os.path.split()函数
语法:os.path.split('PATH')

参数说明:

  1. PATH指一个文件的全路径作为参数:
  2. 如果给出的是一个目录和文件名,则输出路径和文件名
  3. 如果给出的是一个目录名,则输出路径和为空文件名

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值