首页 > Python下载单词音频在Ubuntu下失败

Python下载单词音频在Ubuntu下失败

最近在学英语,用anki整理了自己不会的单词,想添加一点单词音频,于是从网上找了一个模板代码,但是由于原代码是win环境下的,自用的ubuntu不起作用,所以修改了一下,但是,修改之后,还是出错,本人业余,希望大家指点一下:
在终端运行,显示错误代码为

lic@DELL:~/Desktop$ python english.py
Traceback (most recent call last):
  File "english.py", line 88, in <module>
    main()
  File "english.py", line 75, in main
    workerNumber=int(sys.argv[1])
IndexError: list index out of range

源代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 10 19:11:19 2016

@author: lic
"""
import threading 
#导入线程模块
import time
#导入计时模块
import fileinput
#导入文件处理模块
import re
#导入正则表达式匹配模块
import urllib2
#导入获取url的模块
import sys
#sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分.



class DownloadWorker(threading.Thread):
    global mutext

    def __init__(self,wordsList,workerIndex):
        threading.Thread._init_(self)
        self.queue=wordsList
        self.index=workerIndex
    def run(self):
        global mutext
        print('worker%d start to work' % (self.index))
        mutex.acquire()
        self.word=self.queue.front()
        mutex.release()
        while self.word!="0":
            url="http://www.iciba.com/"+self.word
            urlContent=urllib2.urlopen(url).read()
            urlList=re.findall('http://res.iciba.com/resource/amp3/.*\.mp3',urlContent)
            try:
                soundData=urllib2.urlopen(urlList[0]).read()
                saveName=self.word+".mp3"
                output=open(saveName,'wb')
                output.write(soundData)
                output.close()
                print('%s:OK                      --Post by worker%d' % (self.word,self.index))
            except:
                print('%s:FAILED                     --Post by worker%d' % (self.word,self.index))
            finally:
                mutex.acquire()
                self.word=self.queue.front()
                mutex.release()
        print('worker%d exit' % self.index)
class WordsList():
    def __init__(self,filePath):
        self.t=[]
        for line in fileinput.input(filePath):
            if(len(line)>1 and line[len(line)-1]=='\n'):
                line=line[0:len(line)-1]
                self.t.append(line)
            else:
                self.t.append(line)
        self.t.append('0')
    def front(self):
        if(self.t[0]!='0'):
            return self.t.pop(0)
        else:
            return self.t[0]
            
            
            
def main():
    global mutex
    mutex=threading.Lock()
    workerNumber=int(sys.argv[1])
    filePath=sys.argv[2]
    wordsList=WordsList(filePath)
    workerPool=[]
    for i in range(0,workerNumber):
        worker=DownloadWorker(wordsList,i)
        workerPool.append(worker)
    for i in range(0,workerNumber):
        workerPool[i].start()
        
        

if __name__ == "__main__":
    main()

麻烦浪费您30秒,贴一下具体是什么错误?


大体看了下,这个脚本运行时需要接收两个参数,第一个是开启下载线程的数量,第二个是单词文件的路径,所以尝试下

python english.py 1 单词文件的路径

单词文件的格式为每个单词占一行

这段代码写的很清楚,最好先看明白再使用

【热门文章】
【热门文章】