2013-10-14 69 views
1

我正在尋找讓queryvars寫出來分開文件。我已經看過它,我很確定我需要將它移動到另一個文件並將其導入到該文件。我很願意聽取建議:尋找寫出來分開文件; Python:

def nestForLoop(): 
    lines = open("ampersand_right_split.txt", 'r').readlines() 
    f = open("newfile3.txt".format(), 'w') 
    for l in lines: 
     if "&" in l: 
      #param, value = str.split("?",1) 
      mainurl,_, query = l.partition('?') 
      queryvars = query.split("&") 
      if len(l) == 0: 
       break 
      print l 
      f.write(l) 
    f.close() 

nestForLoop() 
+2

請在格式化Python代碼時使用空格(它有助於防止縮進錯誤,如您的文章)。另外,我不太瞭解*你在問什麼。 –

+0

我將如何能夠將結果查詢參數拆分爲&字符以獲取不同的查詢參數? @Wayne Werner –

回答

1

點菜大眼夾: 「它看起來像你試圖解析URL」

the urlparse docs

>>> from urlparse import urlparse 
>>> o = urlparse('http://www.example.com/query%28%29.cgi?somevar=thing&someothervar=otherthing') 
>>> o 
ParseResult(scheme='http', netloc='www.example.com', path='/query%28%29.cgi', params='', query='somevar=thing&someothervar=otherthing', fragment='') 

因此,整合這你的榜樣:

from urlparse import urlparse 
def nestForLoop(): 
    lines = open("ampersand_right_split.txt", 'r').readlines() 
    with open("newfile3.txt".format(), 'w') as f: 

     for l in lines: 
      url = urlparse(l) 
      if url.query: 
       #param, value = str.split("?",1) 
       queryvars = url.query # Good to know, but why did we get this again? 
       if len(l) == 0: 
        break 
       print l 
       f.write(l) 

nestForLoop() 
+0

這就像一個魅力,謝謝你! –

+0

我將如何能夠將結果查詢參數拆分爲&字符以獲取不同的查詢參數? –

+0

http://docs.python.org/2/library/urlparse.html#urlparse.parse_qsl –

0
def nestForLoop(): 
lines = open("ampersand_right_split.txt", 'r').readlines() 
f = open("newfile3.txt".format(), 'w') 
g = open("newfile4.txt".format(), 'w') 
for l in lines: 
    if "&" in l: 
     #param, value = str.split("?",1) 
     mainurl,_, query = l.partition('?') 
     queryvars = query.split("&") 
     if len(l) == 0: 
      break 
     print l 
     f.write(l) 
     g.write(queryvars) 
f.close() 
g.close() 

是做到這一點的一種方法!