QQ登录

只需要一步,快速开始

 注册地址  找回密码

tag 标签: python

相关日志

分享 Python解线性规划问题
水木年华zzu 2013-5-17 09:41
1. 使用工具 PULP+GLPK PULP 是 Python PULP 是用 python 写的建模描述语言, GLPK 是线性规划工具 2. 下载、安装 Python 、 PULP 和 GLPK 以 Python 2.7+PULP 1.4.8 +GLPK4.49 为例 Python 下载地址: http://www.python.org/getit/ GLPK 下载地址: http://www.lupaworld.com/proj-cont-id-121212.html PUPL 下载地址: http://www.coin-or.org/download/source/PuLP/ PUPL Windows 安装: 1. 解压下载好的文件(如解压到 C:\Python27 ) 2. 点击开始—运行 键入 cmd 进入命令行,键入 cd C:\Python27\PuLP-1.4.8 更改路径到 setup.py 所在的文件夹 3. 键入 setup.py install 安装 PUPL 4. 测试是否安装成功 import PULP pulp.pulpTestAll() GLPK 安装 1. 解压下载好的文件(如解压到 C:\glpk-4.49 ) 3. 求解过程 Formulate the Objective Function The objective function becomes: min 0:013x 1 + 0:008x 2 The Constraints The constraints on the variables are that they must sum to 100 and that the nutritional requirements are met: 1:000x 1 + 1:000x 2 = 100.0 0:100x 1 + 0:200x 2 = 8.0 0:080x 1 + 0:100x 2 =6.0 0:001x 1 + 0:005x 2 =2.0 0:002x 1 + 0:005x 2 =0.4 Solution to Simplified Problem from pulp import * ##Create the ’prob’ variable to contain the problem data prob = LpProblem("The Whiskas Problem",LpMinimize) x1=LpVariable("ChickenPercent",0,None,LpInteger) x2=LpVariable("BeefPercent",0,None, LpInteger) prob += 0.013*x1 + 0.008*x2 ## The five constraints are entered prob += x1 + x2 == 100 prob += 0.100*x1 + 0.200*x2 = 8.0 prob += 0.080*x1 + 0.100*x2 = 6.0 prob += 0.001*x1 + 0.005*x2 = 2.0 prob += 0.002*x1 + 0.005*x2 = 0.4 # The problem data is written to an .lp file prob.writeLP("WhiskasModel.lp") # The problem is solved using PuLP’s choice of Solver prob.solve(“C:\\glpk-4.49\\w32\\glpsol.exe”) # prob.solve() 也可以,或者将 C:\glpk-4.49\w32\glpsol.exe 加入到 path 用 #prob.solve(glpk()) # The status of the solution is printed to the screen print "Status:", LpStatus for v in prob.variables(): print v.name, "=", v.varValue print "Total Cost of Ingredients per can = ", value(prob.objective) -----------------------Result --------------------------------------- Status: Optimal ChickenPercent = 34.0 BeefPercent = 66.0 Total Cost of Ingredients per can = 0.97
个人分类: 学习心得|3874 次阅读|0 个评论
分享 转:python 时间日期处理汇集
Seawind2012 2012-5-24 15:50
python 时间日期处理汇集 2011-03-14 16:52 ‍#计算精确时间差 #----------------------------- # High Resolution Timers t1 = time . clock () # Do Stuff Here t2 = time . clock () print t2 - t1 # 2.27236813618 # Accuracy will depend on platform and OS, # but time.clock() uses the most accurate timer it can time . clock (); time . clock () # 174485.51365466841 # 174485.55702610247 #----------------------------- # Also useful; import timeit code = ' ' eval ( code ) # t = timeit . Timer ( code ) print "10,000 repeats of that code takes:" , t . timeit ( 10000 ), "seconds" print "1,000,000 repeats of that code takes:" , t . timeit (), "seconds" # 10,000 repeats of that code takes: 0.128238644856 seconds # 1,000,000 repeats of that code takes: 12.5396490336 seconds #----------------------------- import timeit code = 'import random; l = random.sample(xrange(10000000), 1000); l.sort()' t = timeit . Timer ( code ) print "Create a list of a thousand random numbers. Sort the list. Repeated a thousand times." print "Average Time:" , t . timeit ( 1000 ) / 1000 # Time taken: 5.24391507859 ‍#time , datetime , string 类型互相转换 # string - time time.strptime(publishDate,"%Y-%m-%d %H:%M:%S") # time - string time.strftime("%y-%m-%d",t) #string -datetime datetime.strptime(date_string,format) #datetime-string datetime.strftime("%Y-%m-%d %H:%M:%S") strptime formating Directive Meaning Notes %a Locale’s abbreviated weekday name.   %A Locale’s full weekday name.   %b Locale’s abbreviated month name.   %B Locale’s full month name.   %c Locale’s appropriate date and time representation.   %d Day of the month as a decimal number .   %f Microsecond as a decimal number , zero-padded on the left -1 %H Hour (24-hour clock) as a decimal number .   %I Hour (12-hour clock) as a decimal number .   %j Day of the year as a decimal number .   %m Month as a decimal number .   %M Minute as a decimal number .   %p Locale’s equivalent of either AM or PM. -2 %S Second as a decimal number . -3 %U Week number of the year (Sunday as the first day of the week) as a decimal number . All days in a new year preceding the first Sunday are considered to be in week 0. -4 %w Weekday as a decimal number .   %W Week number of the year (Monday as the first day of the week) as a decimal number . All days in a new year preceding the first Monday are considered to be in week 0. -4 %x Locale’s appropriate date representation.   %X Locale’s appropriate time representation.   %y Year without century as a decimal number .   %Y Year with century as a decimal number.   %z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). -5 %Z Time zone name (empty string if the object is naive).   %% A literal '%' character.   ‍#两日期相减 ‍时间差: d1 = datetime.datetime(2005, 2, 16) d2 = datetime.datetime(2004, 12, 31) print (d1 - d2).days starttime = datetime.datetime.now() endtime = datetime.datetime.now() print (endtime - starttime).seconds ‍ #计算当前时间向后10天的时间。 #如果是小时 days 换成 hours d1 = datetime.datetime.now() d3 = d1 + datetime.timedelta(days =10) print str(d3) print d3.ctime() import datetime, calendar #昨天 def getYesterday(): today=datetime.date.today() oneday=datetime.timedelta(days=1) yesterday=today-oneday return yesterday #今天 def getToday(): return datetime.date.today() #获取给定参数的前几天的日期,返回一个list def getDaysByNum(num): today=datetime.date.today() oneday=datetime.timedelta(days=1) li= #两个日期相隔多少天,例:2008-10-03和2008-10-01是相隔两天 def datediff(beginDate,endDate): format="%Y-%m-%d"; bd=strtodatetime(beginDate,format) ed=strtodatetime(endDate,format) oneday=datetime.timedelta(days=1) count=0 while bd!=ed: ed=ed-oneday count+=1 return count #获取两个时间段的所有时间,返回list def getDays(beginDate,endDate): format="%Y-%m-%d"; bd=strtodatetime(beginDate,format) ed=strtodatetime(endDate,format) oneday=datetime.timedelta(days=1) num=datediff(beginDate,endDate)+1 li= #获取当前月份 是一个字符串 def getMonth(): return str(datetime.date.today()) #获取当前天 是一个字符串 def getDay(): return str(datetime.date.today()) def getNow(): return datetime.datetime.now() print getToday() print getYesterday() print getDaysByNum(3) print getDays('2008-10-01','2008-10-05') print '2008-10-04 00:00:00' print str(getYear())+getMonth()+getDay() print getNow()
463 次阅读|0 个评论
分享 python编程基础操作
Seawind2012 2012-5-22 13:59
常用的处理数字类型的内建函数 int(), long(), float() ,bool()和 complex() 用来将其它数值类型转换为相应的数值类型。 所有这些内建函数现在都转变为工厂函数。所谓工厂函数就是指这些内建函数都是类对象,当你调用它们时,实际上是创建了一个类实例。不过,这些函数的使用方法并没有什么改变。如: int('100')返回100; int(4.2)返回4; bool(1)返回True 类(工厂函数) 操作 bool(obj) 返回obj对象的布尔值,也就是obj.__nonzero__()方法的返回值 int(obj, base=10) 返回一个字符串或数值对象的整数表示,类似string.atoi()方法 long(obj, base=10) 返回一个字符或数据对象的长整数表示,类似string.atol()方法 float(obj) 返回一个字符串或数据对象的浮点数表示,类似string.atof()方法 complex(str) 或者 complex(real, imag=0.0) 返回一个字符串的复数表示,或者根据给定的实数(及一个可选的虚数部分)生成一个复数对象。 常用的功能函数 函数 功能 abs(num) 返回 num 的绝对值 coerce(num1, num2) 将num1和num2转换为同一类型,然后以一个元组的形式返回 divmod(num1, num2) 除法-取余运算的结合。返回一个元组(num1/num2,num1 % num2)。对浮点数和复数的商进行下舍入(复数仅取实数部分的商) pow(num1, num2, mod=1) 取 num1 的 num2次方,如果提供 mod参数,则计算结果再对mod进行取余运算 round(flt, ndig=0) 接受一个浮点数 flt 并对其四舍五入,保存 ndig位小数。若不提供ndig 参数,则默认小数点后0位 仅用于整数的函数 函数 功能 hex(num) 将数字转换成十六进制数并以字符串形式返回 oct(num) 将数字转换成八进制数并以字符串形式返回 chr(num) 将ASCII值的数字转换成ASCII字符,范围只能是0 = num = 255 ord(chr) 接受一个 ASCII 或 Unicode 字符(长度为1的字符串),返回相应的ASCII或Unicode 值 unichr(num) 接受Unicode码值,返回 其对应的Unicode字符。所接受的码值范围依赖于你的Python是构建于UCS-2还是UCS-4 布尔数 从Python2.3 开始,布尔类型添加到了Python 中来。尽管布尔值看上去是“True” 和“False,但是事实上是整型的子类,对应与整数的1 和0。下面是有关布尔类型的主要概念: 有两个永不改变的值 True 或False。 布尔型是整型的子类,但是不能再被继承而生成它的子类。 没有__nonzero__()方法的对象的默认值是 True。 对于值为零的任何数字或空集(空列表、空元组和空字典等)在Python 中的布尔值都是False。 在数**算中,Boolean 值的True 和False 分别对应于1 和 0。 以前返回整数的大部分标准库函数和内建布尔型函数现在返回布尔型。 True 和False 现在都不是关键字,但是在Python 将来的版本中会是。 使用decimal 模块 Python代码 from decimal import Decimal aa=Decimal( '0.1' ) print aa+ 2 输出2.1 数字类型相关模块 模块 介绍 decimal 十进制浮点运算类 Decimal array 高效数值数组(字符,整数,浮点数等等) math/cmath 标准C库数**算函数。常规数**算在match模块,复数运算在cmath模块 operator 数字运算符的函数实现。比如 tor.sub(m,n)等价于 m - n random 多种伪随机数生成器 核心模块: random 当你的程序需要随机数功能时,random 模块就能派上用场。该模块包含多个伪随机数发生器,它们均以当前的时间戳为随机数种子。这样只要载入这个模块就能随时开始工作。下面列出了该模块中最常用的函数: randrange() 返回两个整数之间的随机整数,它接受和 range() 函数一样的参数, 随机返回range( stop )结果的一项 uniform() 几乎和 randint()一样,不过它返回的是二者之间的一个浮点数(不包括范围上限)。 random() 类似 uniform() 只不过下限恒等于0.0,上限恒等于1.0 choice() 随机返回给定序列的一个元素
327 次阅读|0 个评论
分享 python web开发常用字符串处理
Seawind2012 2012-5-22 11:13
1 除去空格 strip( ), lstrip( ), rstrip( ) 2 具体可以参考 http://gaogaochao1.blog.163.com/blog/static/79810971201011212439971/ 在编程中,几乎90% 以上的代码都是关于整数或字符串操作,所以与整数一样,Python 的字符串实现也使用了许多拿优化技术,使得字符串的性能达到极致。与 C++ 标准库(STL)中的 std::string不同,python 字符串集合了许多字符串相关的算法,以方法成员的方式提供接口,使用起来非常方便。 字符串方法大约有几十个,这些方法可以分为如下几类(根据 manuals 整理): 类型 方法 注解 填充 center(width ) , ljust(width ), rjust(width ), zfill(width), expandtabs( ) l fillchar 参数指定了用以填充的字符,默认为空格 l 顾名思义,zfill()即是以字符0进行填充,在输出数值时比较常用 l expandtabs()的tabsize 参数默认为8。它的功能是把字符串中的制表符(tab)转换为适当数量的空格。 删减 strip( ), lstrip( ), rstrip( ) *strip()函数族用以去除字符串两端的空白符,空白符由string.whitespace常量定义。 变形 lower(), upper(), capitalize(), swapcase(), title() title()函数是比较特别的,它的功能是将每一个单词的首字母大写,并将单词中的非首字母转换为小写(英文文章的标题通常是这种格式)。 'hello wORld!'.title() 'Hello World!' 因为title() 函数并不去除字符串两端的空白符也不会把连续的空白符替换为一个空格,所以建议使用string 模块中的capwords(s)函数,它能够去除两端的空白符,再将连续的空白符用一个空格代替。 'hello world!'.title() 'Hello World!' string.capwords('hello world!') 'Hello World!' 分切 partition(sep), rpartition(sep), splitlines( ), split( ]), rsplit( ]) l *partition() 函数族是2.5版本新增的方法。它接受一个字符串参数,并返回一个3个元素的 tuple 对象。如果sep没出现在母串中,返回值是 (sep, ‘’, ‘’);否则,返回值的第一个元素是 sep 左端的部分,第二个元素是 sep 自身,第三个元素是 sep 右端的部分。 l 参数 maxsplit 是分切的次数,即最大的分切次数,所以返回值最多有 maxsplit+1 个元素。 l s.split() 和 s.split(‘ ‘)的返回值不尽相同 'hello world!'.split() 'hello world!'.split(' ') 产生差异 的原因在于当忽略 sep 参数或sep参数为 None 时与明确给 sep 赋予字符串值时 split() 采用两种不同的算法。对于前者,split() 先去除字符串两端的空白符,然后以任意长度的空白符串作为界定符分切字符串(即连续的空白符串被当作单一的空白符看待);对于后者则认为两个连续的 sep 之间存在一个空字符串。因此对于空字符串(或空白符串),它们的返回值也是不同的: ''.split() 连接 join(seq) join() 函数的高效率(相对于循环相加而言),使它成为最值得关注的字符串方法之一。它的功用是将可迭代的字符串序列连接成一条长字符串,如: conf = {'host':'127.0.0.1', ... 'db':'spam', ... 'user':'sa', ... 'passwd':'eggs'} ';'.join("%s=%s"%(k, v) for k, v in conf.iteritems()) 'passswd=eggs;db=spam;user=sa;host=127.0.0.1' 判定 isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), istitle(), startswith(prefix ]), endswith(suffix ]) 这些函数都比较简单,顾名知义。需要注意的是*with()函数族可以接受可选的 start, end 参数,善加利用,可以优化性能。 另,自 Py2.5 版本起,*with() 函数族的 prefix 参数可以接受 tuple 类型的实参,当实参中的某人元素能够匹配,即返回 True。 查找 count( sub ]), find( sub ]), index( sub ]), rfind( sub ]), rindex( sub ]) find()函数族找不到时返回-1,index()函数族则抛出ValueError异常 另,也可以用 in 和 not in 操作符来判断字符串中是否存在某个模板。 替换 replace(old, new ), translate(table ) l replace()函数的 count 参数用以指定最大替换次数 l translate() 的参数 table 可以由 string.maketrans(frm, to) 生成 l translate() 对 unicode 对象的支持并不完备,建议不要使用。 编码 encode( ]), decode( ]) 这是一对互逆操作的方法,用以编码和解码字符串。因为str是平台相关的,它使用的内码依赖于操作系统环境,而 unicode是平台无关的,是Python内部的字符串存储方式。unicode可以通过编码(encode)成为特定编码的str,而str也可以通 过解码(decode)成为unicode。 附注: 1)C++ 中可以通过 boost.string_algo 库来获得同样方便的字符串处理能力。 2)这些字符串方法在 python1.6 版本才开始提供,如果你使用的python版本非常老,可能需要使用string模块来获得这些方便的算法。 ==================================================================== Python-字符串操作方法(转) Python-String-Function 字符串中字符大小写的变换: * S.lower() #小写 * S.upper() #大写 * S.swapcase() #大小写互换 * S.capitalize() #首字母大写 * String.capwords(S) #这是模块中的方法。它把S用split()函数分开,然后用capitalize()把首字母变成大写,最后用join()合并到一起 * S.title() #只有首字母大写,其余为小写,模块中没有这个方法 字符串在输出时的对齐: * S.ljust(width, ) #输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。 * S.rjust(width, ) #右对齐 * S.center(width, ) #中间对齐 * S.zfill(width) #把S变成width长,并在右对齐,不足部分用0补足 字符串中的搜索和替换: * S.find(substr, ]) #返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S 中搜索 * S.index(substr, ]) #与find()相同,只是在S中没有substr时,会返回一个运行时错误 * S.rfind(substr, ]) #返回S中最后出现的substr的第一个字母的标号,如果S中没有substr则返回-1,也就是说从右边算起的第一次出现的substr的首字母标号 * S.rindex(substr, ]) * S.count(substr, ]) #计算substr在S中出现的次数 * S.replace(oldstr, newstr, ) #把S中的oldstar替换为newstr,count为替换次数。这是替换的通用形式,还有一些函数进行特殊字符的替换 * S.strip( ) #把S中前后chars中有的字符全部去掉,可以理解为把S前后chars替换为None * S.lstrip( ) * S.rstrip( ) * S.expandtabs( ) #把S中的tab字符替换没空格,每个tab替换为tabsize个空格,默认是8个 字符串的分割和组合: * S.split( ]) #以sep为分隔符,把S分成一个list。maxsplit表示分割的次数。默认的分割符为空白字符 * S.rsplit( ]) * S.splitlines( ) #把S按照行分割符分为一个list,keepends是一个bool值,如果为真每行后而会保留行分割符。 * S.join(seq) #把seq代表的序列──字符串序列,用S连接起来 字符串的mapping,这一功能包含两个函数: * String.maketrans(from, to) #返回一个256个字符组成的翻译表,其中from中的字符被一一对应地转换成to,所以from和to必须是等长的。 * S.translate(table ) #使用上面的函数产后的翻译表,把S进行翻译,并把deletechars中有的字符删掉。需要注意的是,如果S为unicode字符串,那么就不支持 deletechars参数,可以使用把某个字符翻译为None的方式实现相同的功能。此外还可以使用codecs模块的功能来创建更加功能强大的翻译 表。 字符串还有一对编码和解码的函数: * S.encode( ]) #其中encoding可以有多种值,比如gb2312 gbk gb18030 bz2 zlib big5 bzse64等都支持。errors默认值为"strict",意思是UnicodeError。可能的值还有'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 和所有的通过codecs.register_error注册的值。这一部分内容涉及codecs模块,不是特明白 * S.decode( ]) 字符串的测试函数,这一类函数在string模块中没有,这些函数返回的都是bool值: * S.startwith(prefix ]) #是否以prefix开头 * S.endwith(suffix ]) #以suffix结尾 * S.isalnum() #是否全是字母和数字,并至少有一个字符 * S.isalpha() #是否全是字母,并至少有一个字符 * S.isdigit() #是否全是数字,并至少有一个字符 * S.isspace() #是否全是空白字符,并至少有一个字符 * S.islower() #S中的字母是否全是小写 * S.isupper() #S中的字母是否便是大写 * S.istitle() #S是否是首字母大写的 字符串类型转换函数,这几个函数只在string模块中有: * string.atoi(s ) #base默认为10,如果为0,那么s就可以是012或0x23这种形式的字符串,如果是16那么s就只能是0x23或0X12这种形式的字符串 * string.atol(s ) #转成long * string.atof(s ) #转成float 引用: http://www.telitchina.com/www/12/2007-07/36.html ############################################################ 2009年10月9号 Tech Python string python字符串方法 Python-String-Function 字符串中字符大小写的变换: * S.lower() #小写 * S.upper() #大写 * S.swapcase() #大小写互换 * S.capitalize() #首字母大写 * String.capwords(S) #这是模块中的方法。它把S用split()函数分开,然后用capitalize()把首字母变成大写,最后用join()合并到一起 * S.title() #只有首字母大写,其余为小写,模块中没有这个方法 字符串在输出时的对齐: * S.ljust(width, ) #输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。 * S.rjust(width, ) #右对齐 * S.center(width, ) #中间对齐 * S.zfill(width) #把S变成width长,并在右对齐,不足部分用0补足 字符串中的搜索和替换: * S.find(substr, ]) #返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S 中搜索 * S.index(substr, ]) #与find()相同,只是在S中没有substr时,会返回一个运行时错误 * S.rfind(substr, ]) #返回S中最后出现的substr的第一个字母的标号,如果S中没有substr则返回-1,也就是说从右边算起的第一次出现的substr的首字母标号 * S.rindex(substr, ]) * S.count(substr, ]) #计算substr在S中出现的次数 * S.replace(oldstr, newstr, ) #把S中的oldstar替换为newstr,count为替换次数。这是替换的通用形式,还有一些函数进行特殊字符的替换 * S.strip( ) #把S中前后chars中有的字符全部去掉,可以理解为把S前后chars替换为None * S.lstrip( ) * S.rstrip( ) * S.expandtabs( ) #把S中的tab字符替换没空格,每个tab替换为tabsize个空格,默认是8个 字符串的分割和组合: * S.split( ]) #以sep为分隔符,把S分成一个list。maxsplit表示分割的次数。默认的分割符为空白字符 * S.rsplit( ]) * S.splitlines( ) #把S按照行分割符分为一个list,keepends是一个bool值,如果为真每行后而会保留行分割符。 * S.join(seq) #把seq代表的序列──字符串序列,用S连接起来 字符串的mapping,这一功能包含两个函数: * String.maketrans(from, to) #返回一个256个字符组成的翻译表,其中from中的字符被一一对应地转换成to,所以from和to必须是等长的。 * S.translate(table ) #使用上面的函数产后的翻译表,把S进行翻译,并把deletechars中有的字符删掉。需要注意的是,如果S为unicode字符串,那么就不支持 deletechars参数,可以使用把某个字符翻译为None的方式实现相同的功能。此外还可以使用codecs模块的功能来创建更加功能强大的翻译 表。 字符串还有一对编码和解码的函数: * S.encode( ]) #其中encoding可以有多种值,比如gb2312 gbk gb18030 bz2 zlib big5 bzse64等都支持。errors默认值为”strict”,意思是UnicodeError。可能的值还有’ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 和所有的通过codecs.register_error注册的值。这一部分内容涉及codecs模块,不是特明白 * S.decode( ]) 字符串的测试函数,这一类函数在string模块中没有,这些函数返回的都是bool值: * S.startwith(prefix ]) #是否以prefix开头 * S.endwith(suffix ]) #以suffix结尾 * S.isalnum() #是否全是字母和数字,并至少有一个字符 * S.isalpha() #是否全是字母,并至少有一个字符 * S.isdigit() #是否全是数字,并至少有一个字符 * S.isspace() #是否全是空白字符,并至少有一个字符 * S.islower() #S中的字母是否全是小写 * S.isupper() #S中的字母是否便是大写 * S.istitle() #S是否是首字母大写的 字符串类型转换函数,这几个函数只在string模块中有: * string.atoi(s ) #base默认为10,如果为0,那么s就可以是012或0×23这种形式的字符串,如果是16那么s就只能是0×23或0X12这种形式的字符串 * string.atol(s ) #转成long * string.atof(s ) #转成float 1.python字符串通常有单引号(’…’)、双引号(”…”)、三引号(”"”…”"”)或(”’…”’)包围,三引 号包含的字符串可由多行组成,一般可表示大段的叙述性字符串。在使用时基本没有差别,但双引号和三引号(”"”…”"”)中可以包含单引号,三引号 (”’…”’)可以包含双引号,而不需要转义。 2.用(\)对特殊字符转义,如(\)、(’)、(”)。 3.常用字符串内置函数 1)str.count() //返回该字符串中某个子串出现的次数 2)str.find() //返回某个子串出现在该字符串的起始位置 3)str.lower() //将该字符串全部转化为小写 4)str.upper() //转为大写 5)str.split() //分割字符串,返回字串串列表,默认以空格分割 6)len(str) //返回字符串长度 例如: str = ‘Hello, world’ str.count(‘o’) 2 str.find(‘lo’) 3 str.lower() ‘hello, world’ str.upper() ‘HELLO, WORLD’ str.split() str.split(‘,’) len(str) 13 str ‘Hello, world’ 以上所有操作都不会改变字符串本身! 4.正则表达式,re模块 import re 常用函数: 1)compile(): //将正则表达式字符串编译成正则re对象 2)search() //在目标字符串中匹配正则表达式 3)match() //从目标字符串第一个字符开始匹配正则表达 search和match匹配成功返回 MatchObject对象,失败返回None p = re.compile(‘abc’) p.search(‘zabcy’) _sre.SRE_Match object at 0×2a95659030 不先编译成正则re对象也是可以的,上例也可以为: re.search(‘abc’,'xabcy’) _sre.SRE_Match object at 0×2a95659098 compile还可加些标志位,例如:re.I(re.IGNORECASE)忽略大小写 p = re.compile(‘abc’) print p.search(‘xAbCy’) None p = re.compile(‘abc’,re.I) print p.search(‘xAbCy’) _sre.SRE_Match object at 0×2a9565a098 search和match区别见下例: p = re.compile(‘abc’) print p.search(‘xxxabcyyy’) _sre.SRE_Match object at 0×2a95659030 print p.match(‘xxxabcyyy’) None print p.match(‘abcyyy’) _sre.SRE_Match object at 0×2a95659098 4)split() //类似字符串内置函数split() 区别在于:内置split()以确定字符串分割,而正则split函数以正则表达式分割字 例如:以空格(1个或者多个空格)分割: p.split(‘a b c d’) 而内置split分割的结果为: ‘a b c d’.split(‘ ‘) 5)findall() //返回目标字符串中匹配正则表达式中所有子串列表 p = re.compile(‘^( {2}):( {3}):(.+)$’) p.findall(‘as:123:a12′) 上例中正则表达式的子串为3个用括弧括起的,分别为:’ {2}’、’ {3}’、’.+’,分别被as、123、a12匹配,注意此返回的是匹配字符串元组的一维列表。 以上比较常用的正则函数,更多用法请参照python手册。 5.字符串与数字相互转换,string模块 import string string.atoi(str ) //base为可选参数,表示将字符转换成的进制类型 数字转换成字符串可简单了,直接用str() 6.字符与ASCII转换 char- ascii ord() ascii -char chr()
660 次阅读|0 个评论
分享 转:[Python]Unicode转ascii码的一个好方法
Seawind2012 2012-5-22 10:49
写这篇文章的是一位外国人,他遇到了什么问题呢?比如有一个 Unicode 字符串他需要转为 ascii码: title = u"Klüft skräms inför på fédéral électoral große" print title.encode(‘ascii’,'ignore’) Klft skrms infr p fdral lectoral groe 可以看到丢了许多的字符。那么他在探求有没有一个好的方法,可以把类 Ascii 码的字符转为相应的 ascii 码呢?我的确在邮件列表中好象注意到有这么一封邮件。结果他找到方法了: import unicodedata unicodedata.normalize('NFKD', title).encode('ascii','ignore') 'Kluft skrams infor pa federal electoral groe' 可以看到输出结果非常好。 当然对于我们可能很少遇到这样的转换,因为我们要么是汉字,要么是英文,而不是“古怪的英文”。 其中还有让我吃惊的是在他的Blog的左侧有一个项目的链接 IssueTracker 。我又仔细看了看,的确没有错。为什么这么注意呢?因为早在 2003年8月份,我那时还使用过 Zope ,当时就用过这个产品,并且还将其汉化,加入了多用户的支持。具体可以看我的 Zope主页 (极少更新)中的软件下载,你可以看到我处理后的下载链接。很有趣,在这里碰上了作者,而且作者也依然热爱着 Python 。不过现在我已经远离了 Zope ,但他的软件还在维护中,并且越来越棒了。这个问题跟踪系统还有统计功能,不过好象就是用Html作的很有效。反正都是直方图。 在不经意中看到过去的一些东西真是很有趣,感觉世界很巧,兴趣相同也许终有碰上的一天。
338 次阅读|0 个评论
分享 线性优化,python,gurobi
Seawind2012 2012-5-11 21:44
Advanced Planning and Scheduling is a state-of-art subject which has a potential value and application. Although the Mixed Integer Linear Programming(MILP) is publicly viewed as a NP hard question, we could solve it with gurobi that is an honored solver on the python bat.
240 次阅读|0 个评论
qq
收缩
  • 电话咨询

  • 04714969085

关于我们| 联系我们| 诚征英才| 对外合作| 产品服务| QQ

手机版|Archiver| |繁體中文 手机客户端  

蒙公网安备 15010502000194号

Powered by Discuz! X2.5   © 2001-2013 数学建模网-数学中国 ( 蒙ICP备14002410号-3 蒙BBS备-0002号 )     论坛法律顾问:王兆丰

GMT+8, 2024-4-29 18:40 , Processed in 0.227188 second(s), 29 queries .

回顶部