1

我希望让查询变量写出到单独的文件中。我已经研究过了,我很确定我需要将它移动到另一个文件并将其导入到该文件中。我非常愿意接受以下建议:

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()
4

2 回答 2

1

à la Clippy:“看起来您正在尝试解析 URL”

文档_urlparse

>>> 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()
于 2013-10-14T18:43:50.643 回答
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()

是一种方法!

于 2013-10-14T18:44:53.613 回答