Era*_*ndi 2 python split python-3.x
def loadTest(filename):
f=open(filename,'r')
k=0
line=f.readline()
labels=[]
vectors=[]
while line and k<4:
k=k+1
l=line[:-1].split(r'","')
s=float(l[0][1:])
tweet=l[5][:-1]
print(l)
line=f.readline()
f.close()
return
Run Code Online (Sandbox Code Playgroud)
split(r'","')python split方法实际上做了什么?
MYG*_*YGz 10
r'","'的[R是表明它是一个原始字符串.
原始字符串与python字符串有何不同?
该特殊字符失去其内部特殊的意义一个原始字符串.例如,\n是一个python字符串中的换行符,它将在原始字符串中松散它的含义,而只是表示反斜杠后跟n.
string.split()string.split()将断开并拆分string传递的参数并返回列表中的所有部分.该列表不包括拆分字符.
string.split('","')将断开并拆分每个字符串","并返回列表中的所有损坏部分(不包括)","
例如:
print 'Hello world","there you are'.split(r'","')
Run Code Online (Sandbox Code Playgroud)
输出:
['Hello world', 'there you are']
Run Code Online (Sandbox Code Playgroud)
split() 可以做得更多......您可以通过传入一个额外的参数来指定您希望字符串中断的部分.
让我们考虑这个字符串: 'hello,world,there,you,are'
>>>print 'hello,world,there,you,are'.split(',')
['hello', 'world', 'there', 'you', 'are']
Run Code Online (Sandbox Code Playgroud)
>>>'hello,world,there,you,are'.split(',',1)
['hello', 'world,there,you,are']
Run Code Online (Sandbox Code Playgroud)
>>>'hello,world,there,you,are'.split(',',2)
['hello', 'world', 'there,you,are']
Run Code Online (Sandbox Code Playgroud)
来自文档:
如果未指定拆分字符(即分隔符)或者为None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有,则结果将在开头或结尾处不包含空字符串领先或尾随空格.因此,将空字符串或仅由空格组成的字符串拆分为None分隔符将返回[].
例如,
>>>' 1 2 3 '.split()
['1', '2', '3']
>>>' 1 2 3 '.split(None, 1)
['1', '2 3 ']
>>>''.split()
[]
>>>' '.split()
[]
>>>' '.split(None)
[]
Run Code Online (Sandbox Code Playgroud)
.
.
.
你还在寻找更多吗?不要那么贪心:P.只是质问自己?,它会让你变得非贪婪:D(如果你知道正则表达式,你会得到这个笑话)
| 归档时间: |
|
| 查看次数: |
3456 次 |
| 最近记录: |