Python实现随机读取文本N行数据
2014-10-13 14:34
585 查看
工作中需要判断某个文本中的URL是否能正常访问,并且随机获取其中N行能正常访问的URL数据,我的思路是:读取文本每一行数据,用urlopen访问,将返回状态码为200的URL保存到一个列表,获得列表长度,使用random产生一个随机值作为列表下标,获取该行数据。具体实现如下:
import urllib2,random from sets import Set def get_responses(url): global good_list global bad_list if not url.startswith("http:"): http_url = "http://" + url headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:10.0.1) Gecko/20100101 Firefox/10.0.1',} try: request = urllib2.Request(http_url, headers=headers) resp = urllib2.urlopen(request) print url except urllib2.URLError, e: print e bad_list.append(url) return 0 retcode = resp.getcode() if retcode == 200: good_list.append(url) #return 1 else: bad_list.append(url) #return 0 def readFile(): try: urllist = open(r'C:\Users\888\Desktop\urls.txt','r') except IOError: print "file does not exist.\n" for item in urllist: item = item.strip('\n') r = get_responses(item) urllist.close() print "Total URLs: %d, Good URLs:%d, Bad URLs: %d." %((len(good_list)+len(bad_list)),len(good_list),len(bad_list)) def writeFile(linenum): result = [] linelen = len(good_list) while len(result) < int(linenum): s = random.randint(0,linelen-1) result.append(good_list[s]) result = list(Set(result)) # Put the good_url in goodurl.txt file try: goodurl = open(r'C:\Users\888\Desktop\goodurl.txt','w+') except IOError: print "file does not exist.\n" for item in result: goodurl.write(item+'\n') goodurl.close() print "The mission is done, Please check the goodurl.txt file" if __name__ == "__main__": good_list = [] bad_list = [] readFile() writeFile(150)
相关文章推荐
- python读取文本数据写入到数据库及查询优化
- [原创]如何实现MySQL表数据随机读取
- 详解python实现读取邮件数据并下载附件的实例
- python实现从文件中读取数据并绘制成 x y 轴图形
- Python3实现将文件归档到zip文件及从zip文件中读取数据的方法
- python读取文本中数据并转化为DataFrame
- Python实现读取邮箱中的邮件功能示例【含文本及附件】
- Python随机读取文件实现实例
- Python基于csv模块实现读取与写入csv数据的方法
- 实现读取文本数据,在将数据导入mysql
- python实现正弦+余弦图+csv文件数据读取
- Python文件操作:从文本末尾逆序读取数据
- python读取文本数据写入到数据库及查询优化
- Python实现读取TXT文件数据并存进内置数据库SQLite3的方法
- python读取文本、配对、插入数据脚本
- Python 文本挖掘:数据存储和读取
- python读取文本数据到矩阵(用于scikit-learn输入)
- python读取GB级的文本数据,防止memoryError
- Python实现生成随机数据插入mysql数据库的方法