0

以下のテキストファイルを読み込んでいますformat(a.txt)

http://www.example.com/forum/showthread.php?t=779689/images/webcard.jpg 121.10.208.31

www.example.com次に、の部分だけを取得/images/webcard.jpg 121.10.208.31して、同じファイルまたは別のファイルに書き込む必要があります。この場合、私はそれをに書いていb.txtます。

from urlparse import urlparse 
f = open('a.txt','r')
fo = open('b','w')


for line in f:
    fo.write(urlparse(line).netloc+ ' ' + line.split(' ')[1] + ' ' + line.split(' ')[2] + '\n')

上記のコードは次のエラーを出しますか?これを達成する方法は?

    Traceback (most recent call last):
  File "prittyprint.py", line 17, in <module>
    fo.write(urlparse(line).netloc+ ' ' + line.split(' ')[1] + ' ' + line.split(' ')[2] + '\n')
IndexError: list index out of range
4

1 に答える 1

3

ファイルに例外がある可能性がありますa.txt。一部の行には、この形式がない場合があります。あなたはこれを試すことができます -

from urlparse import urlparse 

f = open('a.txt','r')
fo = open('b','w')

for line in f:
    split_line = line.split(' ')
    if len(split_line) >=3:
        fo.write(urlparse(line).netloc+ ' ' + split_line[1] + ' ' + split_line[2] + '\n')
    else:
        print "ERROR: some other line: %s" % (line) #continue on with next line
于 2013-06-16T06:22:39.337 に答える