Beinsearch
4/4/2017 - 8:16 AM

Python例程

Python例程

# python file
import sys
from selenium import webdriver
 
 
def main(a):
    driver = webdriver.Chrome()  # 打开浏览器
    driver.get(a)  # 浏览器打开指定页面
if __name__ == '__main__':
    for i in range(1, len(sys.argv)):
        url = sys.argv[i]
        main(url)


# java file
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class test_1 {
    
    public static void main(String[] args) { 
        try {
           //String a=getPara("car").substring(1),b="D34567",c="LJeff34",d="iqngfao";
           //String[] args1=new String[]{ "python", "D:\\pyworkpeace\\9_30_1.py", a, b, c, d };
           //Process pr=Runtime.getRuntime().exec(args1);
           String url="http://blog.csdn.net/thorny_v/article/details/61417386";
           System.out.println("start;"+url);
           String[] args1 = new String[] { "python", "D:\\pyworkpeace\\9_30.py", url}; 
           Process pr=Runtime.getRuntime().exec(args1);
           BufferedReader in = new BufferedReader(new InputStreamReader(
             pr.getInputStream()));
           String line;
           while ((line = in.readLine()) != null) {
            System.out.println(line);
           }
           in.close();
           pr.waitFor();
           System.out.println("end");
          } 
        catch (Exception e) {
           e.printStackTrace();
          }
        }
    private static String getPara(String string) {
        // TODO Auto-generated method stub
        return null;
    }
}
import requests
def geocode(location):
    parameters = {'location': location, 'key': '9179b974ee9fe645c3495ae7018343c6'}
    base = 'http://restapi.amap.com/v3/geocode/regeo'
    response = requests.get(base, parameters)
    answer = response.json()
    return answer['regeocode']['addressComponent']['province']#.encode('gbk', 'replace')

LatLong = {}
for item in set(list(df['location'])):
    LatLong[item] = geocode(item)
    
import pickle
latlongfile = 'C:/Users/dell/Desktop/LatLong.txt'
f = open(latlongfile, 'wb')
pickle.dump(LatLong, f)
f.close()

import pickle
latlongfile = 'C:/Users/dell/Desktop/LatLong.txt'
f = open(latlongfile, 'rb')
LatLongDict = pickle.load(f)
f.close()

df['province'] = df['location'].map(LatLongDict)
df.head()
#背包问题 
import numpy as np

def solvepackage(volume,value,capacity):
    l = len(volume)
    if capacity<=0:return np.zeros(l,dtype=int)
    if l == 1:
        if volume[0]<=capacity:return [1]
        else:return [0]
    s2 = solvepackage(volume[1:],value[1:],capacity)
    if volume[0]>capacity:
        return np.append(0,s2)
    s1 = solvepackage(volume[1:],value[1:],capacity-volume[0])
    v1 = (s1*value[1:]).sum()
    v2 = (s2*value[1:]).sum()
    if value[0]+v1>=v2:
        return np.append(1,s1)
    else:
        return np.append(0,s2)

size= np.random.randint(3,10)
vol = np.random.randint(1,10,size)
val = np.random.randint(1,10,size)
cap = np.round(vol.sum()*0.6,0)

s = solvepackage(vol,val,cap)
print vol
print val
print cap
print 'scheme:%s' % s
print 'total volume:%d' % (s*vol).sum()
print 'total value :%d' % (s*val).sum()
#search(s)的函数,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,
#并打印出完整路径:
import os
def search(str,dir):
    m=[]
    for x in os.listdir(dir):
        currdir=os.path.join(dir,x)
        if os.path.isfile(currdir) and str in x:
            m.append(currdir)
        elif os.path.isdir(currdir):
            m.extend(search(str,currdir))
    return m

str = raw_input('input str:')
m=search(str,'E:/MyDownloads/PCI_Code Folder')
m.sort()
for line in m:
    print line
def rotatematrix(data):
  #矩阵转置
  newdata=[]
  for i in range(len(data[0])):
    newrow=[data[j][i] for j in range(len(data))]
    newdata.append(newrow)
  return newdata
http://www.cnblogs.com/salomon/archive/2012/05/28/2518648.html
#信息放在characterdata
import xml.dom.minidom
import urllib
page = urllib.urlopen('http://api.map.baidu.com/telematics/v2/weather?location=%E5%90%88%E8%82%A5&ak=B8aced94da0b345579f481a1294c9094')
s = page.read()
dom = xml.dom.minidom.parseString(s)
root = dom.getElementsByTagName('results')
for node in root:
    results = node.getElementsByTagName('result')
    for result in results:
        date = result.getElementsByTagName('date')
        print date[0].childNodes[0].nodeValue
        weather = result.getElementsByTagName('weather')
        print weather[0].firstChild.data        
        temperature = result.getElementsByTagName('temperature')
        print temperature[0].firstChild.data   

#信息放在attrs
import xml.dom.minidom
import urllib
page = urllib.urlopen('http://flash.weather.com.cn/wmaps/xml/china.xml')
s = page.read()
dom = xml.dom.minidom.parseString(s)
root = dom.getElementsByTagName('china')
for node in root:
    cities = node.getElementsByTagName('city')
    for city in cities:
        print '%5s%6s%15s' % (city.attributes["cityname"].value,city.attributes["stateDetailed"].value,city.attributes["windState"].value)
#SAX解析XML
import urllib
from xml.parsers.expat import ParserCreate
import re
# 解析天气预报
# 百度天气
xml = ''
try:
    page = urllib.urlopen('http://api.map.baidu.com/telematics/v2/weather?location=%E4%B8%8A%E6%B5%B7&ak=B8aced94da0b345579f481a1294c9094')
    xml = page.read()
finally:
    page.close()
# print xml


class BaiduWeatherSaxHandler(object):
    def __init__(self):
        self._weather = dict()
        self._count = 0
        self._current_element = ''

    def start_element(self, name, attrs):
        if name == 'result':
            self._count += 1
            self._weather[self._count] = dict()
        self._current_element = name

    def end_element(self, name):
        pass

    def char_data(self, text):
        # 排除换行符和空白内容
        re_str = '^[\n|\s]+$'
        if self._current_element and not re.match(re_str, text) and self._weather:
            self._weather[self._count][self._current_element] = text

    def show_weather(self):
        for v in self._weather.values():
            print v['date'], '\t'*(7-len(v['date'])), v['temperature'], v['weather'], v['wind']

handler = BaiduWeatherSaxHandler()
parser = ParserCreate()

parser.returns_unicode = True
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data

parser.Parse(xml)

handler.show_weather()
# 百度是信息放在characterdata里的,还有一种放在attrs里的可以自己试试
# url = 'http://flash.weather.com.cn/wmaps/xml/china.xml'
#coding:utf-8
import numpy as np
import random
import matplotlib.pyplot as plt

# ----------------------PSO参数设置---------------------------------
class PSO():
    def __init__(self, pN, dim, max_iter, fitfunc):
        self.w = 0.8
        self.c1 = 2
        self.c2 = 2
        self.r1 = 0.6
        self.r2 = 0.3
        self.pN = pN  # 粒子数量  
        self.dim = dim  # 搜索维度  
        self.max_iter = max_iter  # 迭代次数
        self.fitfunc = fitfunc
        self.X = np.zeros((self.pN, self.dim))  # 所有粒子的位置和速度  
        self.V = np.zeros((self.pN, self.dim))
        self.pbest = np.zeros((self.pN, self.dim))  # 个体经历的最佳位置和全局最佳位置  
        self.gbest = np.zeros((1, self.dim))
        self.p_fit = np.ones(self.pN)*1e10  # 每个个体的历史最佳适应值  
        self.fit = 1e10  # 全局最佳适应值  

# ---------------------初始化种群----------------------------------
    def init_Population(self):
        for i in range(self.pN):
            for j in range(self.dim):
                self.X[i][j] = random.uniform(0, 1)
                self.V[i][j] = random.uniform(0, 1)

# ----------------------更新粒子位置----------------------------------
    def iterator(self):
        fitness = []
        for t in range(self.max_iter):
            for i in range(self.pN):  # 更新gbest\pbest
                temp = self.fitfunc(self.X[i])
                if (temp < self.p_fit[i]):  # 更新个体最优
                    self.p_fit[i] = temp
                    self.pbest[i] = self.X[i]
                    if (self.p_fit[i] < self.fit):  # 更新全局最优
                        self.fit = self.p_fit[i]
                        self.gbest = self.X[i]
            for i in range(self.pN):
                self.V[i] = self.w * self.V[i] + self.c1 * self.r1 * (self.pbest[i] - self.X[i]) \
                            + self.c2 * self.r2 * (self.gbest - self.X[i])
                self.X[i] = self.X[i] + self.V[i]
            fitness.append(self.fit)
            print(self.fit)  # 输出最优值
        return fitness

# ---------------------目标函数Sphere函数-----------------------------
def sphere(x):
    sum = 0
    length = len(x)
    x = x ** 2
    for i in range(length):
        sum += x[i]
    return sum

# ----------------------程序执行-----------------------
my_pso = PSO(pN=30, dim=5, max_iter=100, fitfunc=sphere)
my_pso.init_Population()
fitness = my_pso.iterator()  
from collections import OrderedDict
#OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key
class LastUpdatedOrderedDict(OrderedDict):

    def __init__(self, capacity):
        super(LastUpdatedOrderedDict, self).__init__()
        self._capacity = capacity

    def __setitem__(self, key, value):
        containsKey = 1 if key in self else 0
        if len(self) - containsKey >= self._capacity:
            last = self.popitem(last=False)
            print 'remove:', last
        if containsKey:
            del self[key]
            print 'set:', (key, value)
        else:
            print 'add:', (key, value)
        OrderedDict.__setitem__(self, key, value)