2016-12-04 98 views
2
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 

誰能告訴我什麼R ' 「」' 蟒蛇分裂法裏面實際上沒有python split(r'「,」')是什麼意思?

+3

http://stackoverflow.com/questions/2081640/what-exactly-do-u-和-r-string-flags-do-in-python-and-what-are-raw-string-l – Jakub

+2

該文檔可以。 https://docs.python.org/2/library/stdtypes.html#str.split –

回答

9

原始字符串VS Python字符串

r'","'

[R指示這是一個原始字符串

原始字符串如何與Python字符串不同?

特殊字符鬆內一個原始字符串他們特殊的意義。例如,\n是一個python字符串內的換行符,它將鬆散它在原始字符串中的含義,並且僅僅意味着反斜槓後跟n。

string.split()

string.split()將打破和傳遞,並在列表中返回的所有零件的參數分裂string。該列表將不包括拆分字符。

string.split('","')將打破,並在每個","分割字符串和排除","

如列表返回所有破損部分:

print 'Hello world","there you are'.split(r'","') 

輸出:

['Hello world', 'there you are'] 



split()可以做得更多...

可以指定你要多少個零件串通過傳遞一個額外的參數闖入。

讓我們考慮這樣的字符串:'hello,world,there,you,are'

  1. 上所有逗號分割和斷裂成n + 1份,其中n是逗號的數目:
>>>print 'hello,world,there,you,are'.split(',') 
['hello', 'world', 'there', 'you', 'are'] 
  • 第一個逗號分割並分成兩部分。
  • >>>'hello,world,there,you,are'.split(',',1) 
    ['hello', 'world,there,you,are'] 
    
    上的第一和第二逗號
  • 分裂和破碎成3份。等等...
  • >>>'hello,world,there,you,are'.split(',',2) 
    ['hello', 'world', 'there,you,are'] 
    

    甚至更​​多...

    從文檔:

    如果拆分字符(縣),即分離未指定或無時,一個不同的分割算法應用:將連續空格運行視爲單個分隔符,並且如果字符串具有前導空格或結尾空格,則結果將不包含開始或結束處的空字符串。因此,將空字符串或只包含空格的字符串拆分爲無分隔符將返回[]。

    例如,

    >>>' 1 2 3 '.split() 
    ['1', '2', '3'] 
    
    >>>' 1 2 3 '.split(None, 1) 
    ['1', '2 3 '] 
    
    >>>''.split() 
    [] 
    
    >>>' '.split() 
    [] 
    
    
    >>>'  '.split(None) 
    [] 
    

    甚至...







    什麼?

    你還在尋找更多的東西還不夠嗎?不要那麼貪婪:P。 只問自己?,它會讓你不貪心:D(如果你知道正則表達式,你會得到笑話)

    +3

    很好的解釋。謝謝 – Erandi