Python 怎么对csv中的zzzz中国yyyy日本/m/d h:mm这一列进行排序,有没有代码,有代码加分

这篇文章主要介绍了正则表达式实现将MM/DD/YYYY格式的日期转换为YYYY-MM-DD格式的方法,是一个比较简单实用的正则替换应用,对于怎能则表达式的学习具有一定的参考借鉴价值,需要的朋友可以参考下 本文实例讲述了正则表达式实现将MM/DD/YYYY格式的日期转换为YYYY-MM-DD格式的方法.分享给大家供大家参考.具体实现方法如下: &html& &head&&title&正则表达式&/title&&/head& &body&
// Validate the date format is yyyy/MM/dd or yyyy-MM-dd // Validate the date format is yyyy/MM/dd // Validate the date format change for yyyy-mm-dd simply reg \/ In order to - split(&/&) In order to split(&-&); function checkDate(theDa
许多读者经常询问一个问题,那就是在将DataSet的内容写成XML时,如何格式化字段数据.最常见的需求,就是希望日期时间值与数值数据能够以所需的格式呈现于XML中. 欲达此目的,可以采用下列两种作法: ◆使用XmlConvert类. ◆将一个XSLT转换套用至DataSet数据的XML表示. 程序范例 本范例是利用XmlConvert类来完成字段的格式化操作. // 导入命名空间. using System.X using System.Data.SqlC using Syst
本文介绍使用python写asp程序代码,大家参考使用吧 一.ASP的平反 想到ASP 很多人会说 &asp语言很蛋疼,不能面向对象,功能单一,很多东西实现不了& 等等诸如此类. 以上说法都是错误的,其一ASp不是一种语言是 微软用来代替CGI的一种web框架,只不过我们一直被扭曲在 vbs就是asp的默认语言,把ASP 和 vbs 之间划了等号. 其二 Asp 功能其实并不单一 此web 提供5个对象 (request. response. server. session. appl
如何用 C++ 为 Python 写 dll 来自: 博客分类: C++ C C# C++ Python OS 1. 先新建一个名为 hello.cpp 的 C++ 源文件: Cpp代码 http://msdn.microsoft.com/en-us/library/zkwh89ks(VS.80).aspx #include &stdio.h& #define DLLEXPORT extern &C& __declspec(dllexport) DLLEXPORT int
前一段工作的时候用到了python写后台系统,需要把一些系统的行为记录下来.本着不要去重复发明轮子的精神,就去搜索了一下python的系统库本身是否有写日志的模块.果然有.python语言作为一门接口简单,标准库强大的语言,果然没有令我失望. 简单的使用方法 python的标准库里的日志系统从Python2.3开始支持.只要import logging这个模块即可使用.如果你想把日志写入指定的一个文件中,只要这样使用: import logging logging.basicConfig(fil
$ F (sessionDuartion) as a long type of time, converted to String type HH: MM: DD format $ F (sessionDuartion). LongValue () &3600? (new SimpleDateFormat ( &HH: mm: ss&). format (new Date (($ F (sessionDuartion). longValue () + $ V (data1970)
这篇文章主要介绍了Python写的服务监控程序实例,本文直接给出实现代码,需要的朋友可以参考下 前言: Redhat下安装Python2.7 rhel6.4自带的是2.6, 发现有的机器是python2.4. 到python网站下载源代码,解压到Redhat上,然后运行下面的命令: # ./configure --prefix=/usr/local/python27 # make # make install 这样安装之后默认不会启用Python2.7,需要使用/usr/local/python
这篇文章主要介绍了python写的一个文本编辑器,大家参考使用吧 #!/usr/bin/env python #-*- coding: utf-8 -*- #============================================================================= # FileName: # Desc: # Author: ToughGuy # Version: 0.0.1 # LastChange:
14:52:11 # H
这篇文章主要介绍了Python写的贪吃蛇游戏例子,练手作品,又好玩又可以学到东西,需要的朋友可以参考下 第一次用Python写这种比较实用且好玩的东西,权当练手吧 游戏说明: * P键控制&暂停/开始& * 方向键控制贪吃蛇的方向 源代码如下: from Tkinter import * import tkMessageBox,sys from random import randint class Grid(object): def __init__(self,master=None
这篇文章主要介绍了使用nodejs.Python写的一个简易HTTP静态文件服务器,分为nodejs和Python两个版本,用类似淘宝的CSS.JS文件加载方式处理静态文件加载,需要的朋友可以参考下 日常开发过程中,我们经常需要修改一些放在 CDN 上的静态文件(如 JavaScript.CSS.HTML 文件等),这个过程中,我们希望能有一种方式将线上 CDN 的目录映射为本地硬盘上的某个目录,这样,当我们在本地修改了某个文件时,不需要发布,刷新后马上能看到效果. 比如,我们的 CDN 域名是
这篇文章主要介绍了Python写的Tkinter程序屏幕居中方法,Tkinter是一个python模块,是一个调用Tcl/Tk的接口,它是一个跨平台的脚本图形界面接口,需要的朋友可以参考下 本文适用场景:想用Tkinter开发界面程序并屏幕居中,但没找到相应的API. 这两天玩了玩Tkinter,感觉不错,就是屏幕居中这个问题在网上搜了很长时间也没 找到答案,最后没办法,看它的文档,用自己的方法实现了. 方法很土,就是获取初始化的窗体大小和屏幕大小,再通过计算得到大体值. 以下是代码: #! /
这篇文章主要介绍了Python写的英文字符大小写转换代码示例,本文例子相对简单,本文直接给出代码实例,需要的朋友可以参考下 几行代码的小工具,用于进行如下转换 TRANSACTIONS ON CLOUD COMPUTING =& Transactions On Cloud Computing orig = 'TRANSACTIONS ON CLOUD COMPUTING' splited = orig.split(' ') handled = '' for word in splited: wo
这篇文章主要介绍了Python写的创建文件夹自定义函数mkdir(),文件夹操作是编程中经常需要的,mkdir函数更是经典中的经典,需要的朋友可以参考下 Python对文件的操作还算是方便的,只需要包含os模块进来,使用相关函数即可实现目录的创建. 主要涉及到三个函数: 1.os.path.exists(path) 判断一个目录是否存在 2.os.makedirs(path) 多层创建目录 3.os.mkdir(path) 创建目录 直接上代码: def mkdir(path): # 引入模块
这篇文章主要介绍了python写xml文件的操作实例,是非常常见的实用技巧,需要的朋友可以参考下 本文实例讲述了python写xml文件的操作的方法,分享给大家供大家参考.具体方法如下: 要生成的xml文件格式如下: &?xml version=&1.0& ?& &!--Simple xml document__chapter 8--& &book& &title& sample xml thing &/title& &
这篇文章主要介绍了python写的ARP攻击代码实例,需要的朋友可以参考下 注:使用这个脚本需要安装scapy 包 最好在linux平台下使用,因为scapy包在windows上安装老是会有各种问题 #coding:utf-8 #example :sudo python arp_dos.py 192.168.1.103 from scapy.all import ARP,send import os,re,sys def get_gateway_ip(): t=os.popen('route -
这篇文章主要介绍了Python写的一个简单DNS服务器实例,需要的朋友可以参考下 因为突然有个邪恶的想法,想在自己的Android平板上面搭建一个DNS服务器,因为平板上之前安装过SL4A和Python的解释器,也想继续学学Python因此,就打算用Python实现了. 在Google上面找了一下,Python实现的DNS,没找到我所希望的答案,因此就决定自己来实现了. 现在所实现的没什么高深的,只是能够对A记录查询进行简单的匹配和回复. 实现的代码如下: ''' Created on 2012
这是一篇「抛砖」与「摆立场」的文章,欢迎有理有据的批判与讨论. 首先摆出个人的立场:「代码司法」,在一定程度上,是可以的,至少交互式断案是可行的.至于其「必要性」,则在于进一步去除司法过程中的「不公正」,并且赋予司法过程以「可重复性」. 1 首先举一个实际的例子,下图是1998年袭击东非大使馆的人员网络: 1998年袭击东非大使馆的人员网络 我们要找到他们的合作关系,也就是找出他们中有几个团体,这是可以通过代码做到的: clique = FindClique[g, {5}, All] {{&Fa
这篇文章主要介绍了Python写的Socks5协议代理服务器,代码来自网上,需要的朋友可以参考下 直接上代码: #!/usr/bin/python # Filename s5.py # Python Dynamic Socks5 Proxy # Usage: python s5.py 1080 # Background Run: nohup python s5.py 1080 & import socket, sys, select, SocketServer, struct, time cla
这篇文章主要介绍了Python写的PHPMyAdmin暴力破解工具代码,同时涉及了CVE- MySQL Authentication Bypass Vulnerability漏洞的利用,需要的朋友可以参考下 PHPMyAdmin暴力破解,加上CVE- MySQL Authentication Bypass Vulnerability漏洞利用. #!/usr/bin/env python import urllib import urllib2 import c
这篇文章主要介绍了Python写的Discuz7.2版faq.php注入漏洞工具,全自动的一款注入工具,针对Discuz7.2版,需要的朋友可以参考下 Discuz 7.2 faq.php全自动利用工具,getshell 以及dump数据,python 版的uc_key getshell部分的代码来自网上(感谢作者) 实现代码: #!/usr/bin/env python # -*- coding: gbk -*- # -*- coding: gb2312 -*- # -*- coding: u
这篇文章主要介绍了python写的一个分析squid访问日志的小程序,本文实现的目标是统计access.log中的ip数目,需要的朋友可以参考下 这两周组里面几位想学习python,于是我们就创建了一个这样的环境和氛围来给大家学习. 昨天在群里,贴了一个需求,就是统计squid访问日志中ip 访问数和url的访问数并排序,不少同学都大体实现了相应的功能,我把我简单实现的贴出来,欢迎拍砖: 日志格式如下: %ts.%03tu %6tr %{X-Forwarded-For}&h %Ss/%03Hs
昨天在写代码中一不小心将UserControl写成了Control,将原来应该继承自System.Web.UI.UserControl的用户控件,比如下面的BlogStats: &%@ Control Language=&c#& Inherits=&CNBlogs.Web.BlogStats& %& public class BlogStats : UserControl { protected override void OnLoad(EventArg
如果你是我的长期读者,那么你应该知道我在寻找一个完美备份程序,最后我写了一个基于bup的我自己的加密层. 在写encbup的时候,我对仅仅恢复一个文件就必须要下载整个巨大的档案文件的做法不甚满意,但仍然希望能将EncFS和rdiff-backup一起使用来实现可远程挂载.加密.去重.版本化备份的功能. 再次试用obnam后(??乱痪洌核?故锹?某銎?,我注意到了它有一个mount命令.深入研究后,我发现了fuse-python和fusepy,感觉用Python写一个FUSE文件系统应该挺简单的.
今天突然超级的冷啊,要穿羽绒咯~练习,python写个天气预报小玩意,直接代码吧: 群博录:每个博客,都有故事--
原本该写成 x = 2; 结果不小心多打了个等号,写成了 x == 2; . 写了如下代码验证,文件名保存为 02.c: #include &stdio.h& int main(int argc, char *argv[]) { int x = 0; printf(&%d\n&, x); x == 2; printf(&%d\n&, x); return 0; } gcc 在不开启警告的情况下,没有任何提示信息. &求一个表达式的值,但不使用该
今天初学Python写了一个用于计算指定年指定月日历的脚本 我的Python版本:Python 3.4.2 输入:脚本名 年(4位数字,) 月(1-2位数字,1-12) 输出:打印的指定年月日历信息 Calendar.py import os import sys # check if the number of input is legal if len(sys.argv) != 3: print('Invalid input! Example: 2014 12') os.s
这篇文章主要介绍了Sql中将datetime转换成字符串的方法,需要的朋友可以参考下 一.回顾一下CONVERT()的语法格式:CONVERT (&data_ type&[ length ], &expression& [, style]) 二.这里注重说明一下style的含义:style 是将DATATIME 和SMALLDATETIME 数据转换为字符串时所选用的由SQL Server 系统提供的转换样式编号,不同的样式编号有不同的输出格式:一般在时间类型(datetime,s
今天没事做, 就又练习写计算器程序了. 本来打算用python来写一个简单的支持加减乘除括号的计算器, 后来有加上了变量复制, 比较符, 条件判断, 循环, 最后还加上了函数, 几乎可以说是一个简单的语言了. 以后我也可以说写过一门语言了哈哈. 回到正题. 这里面整理一下这个简单的程序用到的方法, 代码在: https://bitbucket.org/linjunhalida/code-example/src/tip/python/calculator/ 一开始, 我希望实现一个简单的支持加减乘
1.最基本的抓站 import urllib2 content = urllib2.urlopen('http://XXXX').read() 2.使用代理服务器 这在某些情况下比较有用,比如IP被封了,或者比如IP访问的次数受到限制等等. import urllib2 proxy_support = urllib2.ProxyHandler({'http':'http://XX.XX.XX.XX:XXXX'}) opener = urllib2.build_opener(proxy_suppo
在公司里做的一个接口系统,主要是对接第三方的系统接口,所以,这个系统里会和很多其他公司的项目交互.随之而来一个很蛋疼的问题,这么多公司的接口,不同公司接口的稳定性差别很大,访问量大的时候,有的不怎么行的接口就各种出错了. 这个接口系统刚刚开发不久,整个系统中,处于比较边缘的位置,不像其他项目,有日志库,还有短信告警,一旦出问题,很多情况下都是用户反馈回来,所以,我的想法是,拿起python,为这个项目写一个监控.如果在调用某个第三方接口的过程中,大量出错了,说明这个接口有有问题了,就可以更快的采
问:现在已经可以用javascript(nodejs)写服务端的代码,但如果是为了语言一致性的话,为什么没人去做过python在浏览器端的实现呢? 答:这个问题其实与Python没半毛钱关系,比如可以把最后一句改成为什么没人去做ruby在浏览器端的实现呢?还可以改成为什么没人去做java在浏览器端的实现呢?等等. 从历史的角度来看,JavaScript的发展一直与浏览器密不可分,最初由网景公司的Brendan Eich设计,叫LiveScript,后与Sun公司合作,改为JavaScript.后
下载地址:http://2.myrestful.sinaapp.com/ 目录 一.Python概述7 1)第一个Python程序8 1.为什么要学习Python9 2.代码块与缩进的差异9 3.语句结尾的差异9 4.注释方法10 5.入口方法10 6.import与using语句10 2)小结10 二.基本数据类型10 1)第一个程序的解析10 2)变量的命名规范12 3)空类型13 4)布尔类型13 5)数值类型13 6)字符串类型14 7)全局变量15 三.基本数据类型-列表(list[]
关于 if (i = 3)的情况,写了如下的代码,文件保存为 01.c: #include &stdio.h& int main(int argc, char *argv[]) { int i = 0; printf(&if前:i = %d\n&, i); if (i = 3) ; printf(&if后:i = %d\n&, i); return 0; } 在使用gcc进行编译时,如果不开启警告选项,不会有任何的警告: $ gcc 01.c 如果开启警
mp3play 网站 : https://github.com/michaelgundlach/mp3play mp3play 是一个用 Python 开发的 MP3 播放器,界面非常简单,无需安装其他的模块.可以嵌入到应用程序中以至此MP3音乐播放. 授权协议: Apache 开发语言: Python 操作系统: Windows
写了个图片蜘蛛人玩玩,抓了几个网页试试,感觉不不错.核心的代码可能20行也不到,简洁明了,嘻嘻.废话少说,翠花,上代码 #coding=utf-8 import os import sys import re import urllib URL_REG = re.compile(r'(http://[^///]+)', re.I) IMG_REG = re.compile(r'&img[^&]*?src=([/'&])([^/1]*?)/1', re.I) def download(
首先需要说明的一点,无论是Winform,还是Webform,都有很成熟的日历控件,无论从易用性还是可扩展性上看,日期的选择和校验还是用日历控件来实现比较好. 1概述 首先需要说明的一点,无论是Winform,还是Webform,都有很成熟的日历控件,无论从易用性还是可扩展性上看,日期的选择和校验还是用日历控件来实现比较好. 前几天在CSDN多个版块看到需要日期正则的帖子,所以整理了这篇文章,和大家一起讨论交流,如有遗漏或错误的地方,还请大家指正. 日期正则一般是对格式有要求,且数据不是直接由用
这篇文章主要介绍了用Python进行行为驱动开发的入门教程,本文也对BDD的概念做了详细的解释,需要的朋友可以参考下 为驱动开发(Behavior-Driven Development,BDD)是一种卓越的开发模式.能帮助开发者养成日清日结的好习惯,从而避免甚至杜绝&最后一分钟&的情况出现,因此对提高代码质量是大有裨益的.其与Gherkin语法相结合的测试结构及设计形式,使得对团队的全部成员包括非技术人员都具有极好的易读性. 所有代码都必须进行测试,这意味着上线时把系统瑕疵降到最低甚至
oracle 日期函数网上已经有了不少,特我们跟集中一下,免得大家麻烦. 在oracle数据库的开发中,常因为时间的问题大费周章,所以特地将ORACLE数据的日期函数收藏致此.乃供他日所查也. add_months(d,n) 日期d加n个月 last_day(d) 包含d的月?的最后一天的日期 new_time(d,a,b) a?区的日期和??d在b?区的日期和?? next_day(d,day) 比日期d?,由day指定的周几的日期 sysdate 当前的系?日期和?? greatest(d1
小说作者 &当卡利姆多大陆初脱魔爪,生机复苏.是你征服了荒夷四起的周遭,是你改造了不毛之地,为子嗣造就生存的摇篮--&这句文字来源于一部描写网络游戏&魔兽世界&中的英雄的小说.小说名为&KingofTauren&(注:Tauren即牛头人之王,魔兽中的神话角色),长达46万字.小说停笔时,作者杨力还是南平市一名初三未毕业的稚嫩男生. 今年上半年,杨力将小说发到网上,引起了不小的轰动. 一篇范文激发出写作热情 今年17岁的杨力在南平一中读高三,成绩中等偏上,父亲是
这篇文章主要介绍了使用Python的Scrapy框架编写web爬虫的简单示例,使用Python编写爬虫是Python应用方面最得意的利器,Scrapy框架正是为爬虫而生,需要的朋友可以参考下 在这个教材中,我们假定你已经安装了Scrapy.假如你没有安装,你可以参考这个安装指南. 我们将会用开放目录项目(dmoz)作为我们例子去抓取. 这个教材将会带你走过下面这几个方面: 创造一个新的Scrapy项目 定义您将提取的Item 编写一个蜘蛛去抓取网站并提取Items. 编写一个Item Pipel
主要是利用Windows的脚本功能来计算要删除文件的截止日期,然后for加dir命令来提取文件的日期进行判断 下是备份的批处理,添加到&计划任务&中,设定时间自动运行 @echo off rem 格式化日期 rem date出来的日期是& 星期三&,不能直接拿来使用,所以应该先格式化一下 rem 变成我们想要的.date:~0,4的意思是从0开始截取4个字符 set d=%date:~0,4%%date:~5,2%%date:~8,2% rem
Django是一个开源的Web应用框架,由Python写成.采用MVC的软件设计模式,主要目标是使得开发复杂的.数据库驱动的网站变得简单.Django注重组件的重用性和&可插拔性&,敏捷开发和DRY法则(Don't Repeat Yoursef). 花了两周时间,利用工作间隙时间,开发了一个基于Django的项目任务管理Web应用.项目计划的实时动态,可以方便地被项目成员查看(^_^又重复发明轮子了).从前台到后台,好好折腾了一把,用到:HTML.CSS.JavaScript.Apac
主要知识点:js数组,数字函数,字符串函数,表单验证,hashMap,堆栈,日期函数,call函数 等. next:js正则表达式,闭包,apply,callee,事件相关函数,Cookie等 1.javascript的数组API //定义数组 var pageIds = new Array(); pageIds.push('A'); 数组长度 pageIds. //shift:删除原数组第一项,并返回删除元素的值:如果数组为空则返回undefined var a = [1,2,3
Spring MVC中基于自定义Editor的表单数据处理技巧.需要的朋友可以过来参考下,希望对大家有所帮助 面向对象的编程方式极大地方便了程序员在管理数据上所花费的精力.在基于Spring MVC的Web开发过程当中,可以通过对象映射的方式来管理表单提交上来的数据,而不用去一个一个地从request中提取出来.另外,这一功能还支持基本数据类型的映射.例如in.long.float等等.这样我们就能从传统单一的String类型中解脱出来.然而,应用是灵活的.我们对数据的需求是千变万化的.有些时候
方便使用js的朋友,把下面的函数找到你想要的功能函数,复制部分判断输入文本是否为身份证号码,如为不正确则提示 //js常用函数 更新 取自网络 function $(id) { return document.getElementById(id); } /************** 函数:getElementsByClassName 使用方法: 获取document内的超链接class是&info-links&的. getElementsByClassName(do
原文 http://www.hetland.org/python/instant-hacking.php Instant Hacking[译文] 译者: 肯定来过 这是一篇简短的关于python程序设计语言的入门教程,原文在这里,翻着词典翻译了来! 这是一份对编程艺术的简短介绍,其中的例子是用python写成的.(如果你已经知道了该如何编程,但是想简单了解一下python,你可以查阅我的另一篇文章Instant Python.)这篇文章已经被翻译为意大利.波兰.日本.塞尔维亚以及巴西葡萄亚语等许
使用py2exe生成windows服务在win7下可以正常运行,但是到了xp下面可以安装,但是无法启动 报&服务没有及时响应或控制请求&的错误,改用pyinstaller生成也是不行:查资料后修改setup.py如下即可,服务名.脚本名请自行替换: #!/usr/bin/python #-*-coding:cp936-*- from distutils.core import setup import py2exe class Target: def __init__(self, **
以下做法与你将读到的内容完全背离,那就是为你的表单点缀漂亮的按钮,颜色以及排版甚至充沛的jQuery插件,这些都无助于可用性.事实上,这么做你只是(通过没有归整过的方式)实现了表单可用性的三分之一. 在这篇文章中,我们将提供便于你执行且切实可行的规范.这些精心编排制作的规范是来源于可用性测试,实施现场测试,网络站点追踪,视线追踪,网页在线分析及客户支持部门获取的客户投诉. 为什么网络表单可用性如此重要 ISO 9241标准将网站可用性定义为&高效,有效地满足特定用户在某个环境中达到特定目的.&q
这篇文章主要是对我收集的一些文章的摘要.因为已经有很多比我有才华的人写出了大量关于如何成为优秀Python程序员的好文章. 我的总结主要集中在四个基本题目上:函数式编程,性能,测试,编码规范.如果一个程序员能将这四个方面的内容知识都吸收消化,那他/她不管怎样都会有巨大的收获. 函数式编程 命令式的编程风格已经成为事实上的标准.命令式编程的程序是由一些描述状态转变的语句组成.虽然有时候这种编程方式十分的有效,但有时也不尽如此(比如复杂性) -- 而且,相对于声明式编程方式,它可能会显得不是很直观.
Copyright (C) , All Rights Reserved.
版权所有 闽ICP备号
processed in 0.061 (s). 11 q(s)python部分内容存档
时间: 17:27:08
&&&& 阅读:295
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&笨办法学python. 1
Ec6字符串和文本... 1
Ec10 转义字符... 1
Ec11提问... 1
raw_input和input的区别... 1
Ec12提示别人... 1
ec13 参数,解包,变量... 1
ec14提示和传递... 1
Ec15读取文件... 1
Ec16读写文件... 1
ec17更多文件操作... 1
ec18命名,变量,代码,函数... 1
ec19函数和变量... 1
ec20函数和文件... 1
ec21函数可以返回东西... 1
Ec25自己写函数作为脚本,文档注释... 1
Ec31 if & raw_input() 1
ec33while. 1
ec35用函数写的一个小的选择游戏... 1
ec39列表的操作... 1
ec40字典... 1
map 函数应用... 1
ec41函数写小型地图游戏,raw_input提示给答案... 1
ec随机数用法... 1
getattr用法... 1
Ec42class写ec41的游戏... 1
ec处理异常try & except 1
From实验楼... 1
Pathbao.py. 1
sy1 glob. 1
Sy2 os包... 1
shutil包... 1
Pickle包... 1
subprocess包... 1
thread包... 1
multiprocessing包... 1
读取中文... 1
Sy6.py线程实验售票系统... 1
sy6.py用类实现... 1
ascii.py argparse操作分解... 1
sy8.py argparse 操作最终... 1
pic_change_str.py 实验楼图片转字符画课程... 1
2048系列代码... 1
主程序代码... 1
2048cp zip/for的用法... 1
2048cp1 curse的颜色设置。。... 1
2048cp2研究curses的一些用法,很奇怪,还不精... 1
2048cp3#边框的画法,控制数组大小和里面值是否出现... 1
2048cp4学习defaultdict的用法... 1
2048read_input.py. 1
2048hasatta的用法... 1
2048format的用法... 1
2048clear 1
Jianming. 1
class_inherit 1
class_init 1
finally. 1
list_comprehension. 1
my_module. 1
my_module1. 1
Pickling. 1
powersum.. 1
print_one_line. 1
threading. 1
threading2. 1
try_except 1
菜鸟教程... 1
Using_copy. 1
using_dict 1
using_file. 1
using_list 1
using_name. 1
Using_slice. 1
using_str 1
using_tuple. 1
菜鸟教程例子... 1
Mysql教程... 1
1.创建数据库... 1
2.删除数据库... 1
3.创建表... 1
4.删除表... 1
5修改表... 1
(1)&&&&& 修改表类型,语法如下:... 1
(2)增加表字段,语法如下:... 1
(3)删除表字段,语法如下:... 1
(4)字段改名,语法如下:... 1
(5)修改字段排列顺序... 1
(6)表改名,语法如下:... 1
DML 语句... 1
插入记录... 1
更新记录... 1
删除记录... 1
查询记录... 1
(1)&&&& 查询不重复的记录。... 1
(2)条件查询... 1
(3)排序和限制... 1
(4)聚合... 1
Ashdgasbjdb
笨办法学python
Ec6字符串和文本
x=‘there are %d types of people‘ % 10
binary=‘binary‘
do_not="don‘t"
y=‘those who know %s and those who %s.‘%(binary,do_not)
print(‘I saied: %r.‘ % x)
print("I also said: ‘%s‘."% y)
hilarious = False
joke_evaluation="Isn‘t that joke so funny?! %r"
print(joke_evaluation % hilarious)
w="this is the left side of.."
e=‘a string with a right side.‘
print(w+e)
print(‘Mary had a little lamb.‘)
print("its fleece was white as %s."% ‘snow‘)
print("And everywhere that Mary went.")
print ("." * 10) #what the fk这边是出现10次
end2=‘h‘
end3=‘e‘
end4=‘e‘
end5=‘s‘
end6=‘e‘
end7=‘B‘
end8=‘u‘
end9=‘r‘
end10=‘g‘
end11=‘e‘
end12=‘r‘
print(end1+end2+end3+end4+end5+end6,)
print(end7+end8+end9+end10+end11+end12)
formatter=‘%r %r %r %r‘
print(formatter %(1,2,3,4))
print(formatter %(‘one‘,‘two‘,‘three‘,‘four‘))
print(formatter %(True,False,False,True))
print(formatter %(formatter,formatter,formatter,formatter))
print(formatter % (
&&& "I had this thing.",
&&& ‘That you could type up right.‘,
&&& "But it didn‘t sing.",
&&& "So I said goodnight."
days ="\nMon Tue Wed Thu Fri Sat Sun"
months="\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print("Here are the days:",days)
print("\n\nHere are the months:",months)
#print(‘what fc‘)#这样写就不会换行,很正常的写法
print(‘‘‘
‘‘‘)#这样写就会换行,应该是‘‘‘起作用
Ec10 转义字符
#--coding:utf-8 --
tabby_cat ="\tI‘m tabbed in."
persian_cat ="I‘m split\non a line."
backslash_cat="I‘m \\ a \\ cat."
fat_cat="""
I‘ll do a list:
\t* Cat food
\t* Fishes
\t* Catnip\n\t* Grass
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)
所有的转义字符和所对应的意义:
ASCII码值(十进制)
退格(BS) ,将当前位置移到前一列
换页(FF),将当前位置移到下页开头
换行(LF) ,将当前位置移到下一行开头
回车(CR) ,将当前位置移到本行开头
水平制表(HT) (跳到下一个TAB位置)
垂直制表(VT)
代表一个反斜线字符‘‘\‘
代表一个单引号(撇号)字符
代表一个双引号字符
  &&&&& 代表一个问号
  &&&&& 063
空字符(NULL)
1到3位八进制数所代表的任意字符
三位八进制
1到2位十六进制所代表的任意字符
二位十六进制
注意:区分,斜杠:"/" 与 反斜杠:"\" ,此处不可互换
print "How old are you?",
age=raw_input()
print "How tall are you?",
height =raw_input()
print "How much do you weigh?",
weight =raw_input()
print "So,you‘re %r old,%r tall and %r heavy." %(age,height,weight)
raw_input和input的区别
1 &&& raw_input_A = raw_input("raw_input: ")
&2 raw_input: abc
&3& &&& input_A = input("Input: ")
&4 Input: abc
&6 Traceback (most recent call last):
&7&& File "&pyshell#1&", line 1, in &module&
&8&&&& input_A = input("Input: ")
&9&& File "&string&", line 1, in &module&
10 NameError: name ‘abc‘ is not defined
11& &&& input_A = input("Input: ")
12 Input: "abc"
1 &&& raw_input_B = raw_input("raw_input: ")
2 raw_input: 123
3& &&& type(raw_input_B)
4& &type ‘str‘&
5 &&& input_B = input("input: ")
6 input: 123
7 &&& type(input_B)
8 &type ‘int‘&
例子 1 可以看到:这两个函数均能接收 字符串 ,但 raw_input() 直接读取控制台的输入(任何类型的输入它都可以接收)。而对于 input() ,它希望能够读取一个合法的 python 表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。
例子 2 可以看到:raw_input() 将所有输入作为字符串看待,返回字符串类型。而 input() 在对待纯数字输入时具有自己的特性,它返回所输入的数字的类型( int, float );同时在例子 1 知道,input() 可接受合法的 python 表达式,举例:input( 1 + 3 ) 会返回 int 型的 4 。
就是说input处理数字的时候会确定类型,而raw_input全都是字符型,无所谓。
Ec12提示别人
age=raw_input("How old are you?")
height =raw_input("How tall are you?")
weight =raw_input("How much do you weigh?")
print "So,you‘re %r old, %r tall and %r heavy."%(age,height,weight)
ec13 参数,解包,变量
from sys import argv
script, first, second, third = argv
print "The script is called:" , script
print "Your first variable is:",first
print "Your second variable is:",second
print "Your third variable is:",third
ec14提示和传递
from sys import argv
script, user_name=argv
prompt = ‘‘
print "Hi %s, I‘m the %s script." %(user_name,script)
print "I‘d like to ask you a few questions."
print "Do you like me %r?" %user_name
likes=raw_input(prompt)
print "Where do you live %s?" % user_name
lives =raw_input(prompt)
print "What kind of computer do you have?"
computer =raw_input(prompt)
Alright, so you said %r about likeing me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" %(likes,lives,computer )
#搞清楚了%r和%s的区别,r是后面引用字符串的时候会接引号,而s不会接引号
Ec15读取文件
#coding=utf-8 #添加这个可以使用中文注释
from sys import argv
script, filename= argv#"获取文件名"
txt=open(filename)#Python -m pydoc open来查看相关意思
print("Here‘s your file %r:")% filename
print txt.read()
print(txt.closed)
txt.close()
print(txt.closed)
# print "Type the filename again:"
# file_again=raw_input("&&&&")
# txt_again= open(file_again)
# print txt_again.read()
Ec16读写文件
#coding=utf-8
from sys import argv
script,filename=argv
print"We‘re going to erase %r." %filename
print"If you don‘t want that,hit CTRL-C (^C)."
print"If you do want that,hit RETURN."
raw_input("?")
print"Opening the file..."
target=open(filename,‘w‘)
print"Truncating the file.&& Goodbye!"
target.truncate()
print"Now I‘m going to ask you for three lines."
line1=raw_input("line1:")
line2=raw_input("line2:")
line3=raw_input("line3:")
print"I‘m going to write these to the file."
#target.write(line1 & "\n" & line2 & "\n" & line3 )#这种连接的用法找找看
target.write("%s\n%s\n%s" %(line1,line2,line3))#此刻我想说还是我大结构化靠谱!
print"And finally, we close it."
target.close()
ec17更多文件操作
#coding=utf-8
from sys import argv
from os.path import exists
script,from_file,to_file = argv
print "Copying from %s to %s" %(from_file,to_file)
#we could do these two on one line too,how?
input =open(from_file)
indata=input.read()
print ‘‘‘The input file is %d bytes long,
Does the output file exist?%r,
Ready,hit RETURN to continue,CTRL-C to abort.
‘‘‘%(len(indata),exists(to_file))#用了‘‘‘分行显示,格式化不晓得能不能分行。
raw_input()
output=open(to_file,‘w‘)
output.write(indata)
print"Alright,all done."
output.close()
input.close()
ec18命名,变量,代码,函数
#coding=utf-8
#This one is like your scripts with argv
def print_two(*args):
&&& arg1,arg2,arg3=args
&&& print"arg1:%r,arg2:%r,arg3;%s" %(arg1,arg2,arg3)
#ok \, that *args is actually pointless, we can just do this
def print_two_again(arg1,arg2):
&&& print "arg1:%r.arg2:%r" %(arg1,arg2)
#注意区分上下两个的用法&&&
#this just take one arguement
def print_one(arg1):
&&& print"arg1:%r" % arg1
#this one takes no arguement
def printnone():
&&& print "I got nothin‘."
print_two("Zed","Shaw",‘wtf‘)&&&
print_two_again("Zed","Shaw")
print_one("First!")
printnone()
ec19函数和变量
#coding=utf-8
def cheese_and_crackers(cheese_count,boxes_of_crackers):
&&& print"You have %d cheeses!"% cheese_count
&&& print"You have %d boxes of crackers!"% boxes_of_crackers
&&& print"Man that‘s enough for a party!"
&&& print"Get a blanket.\n"
print"We can just give the function numbers directly:"
cheese_and_crackers(20,30)
print"Or, we can use variables from our scripts:"
amount_of_cheese=10
amount_of_crackers=50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
print"We can even do math inside too:"
cheese_and_crackers(10+20,5+6)
print"And we can combine the two,variables and math:"
cheese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)
ec20函数和文件
#coding=utf-8
from sys import argv
script,input_file=argv
def print_all(f):
&&& print f.read()
def rewind(f):
&&& f.seek(0)
def print_a_line(line_count,f):
&&& print line_count,f.readline()#这个是如何实现每一行都读取,是个问题
current_file=open(input_file)&&&
print "First let‘s print the whole file:\n"
print_all(current_file)
print"\nNow let‘s rewind,kind of like a tape."
rewind(current_file)
print"Let‘s print three lines:"
current_line=1
print_a_line(current_line,current_file)
current_line=10
print_a_line(current_line,current_file)
# current_line=current_line+1
# print_a_line(current_line,current_file)
print_a_line(3,current_file)
print_a_line(3,current_file)
print_a_line(3,current_file)#果然不是按照行号来的
ec21函数可以返回东西
#coding=utf-8
def add(a,b):
&&& print"Adding %d+%d"%(a,b)
&&& return a+b
def subtract(a,b):
&&& print"Suntracting%d-%d"%(a,b)
&&& return a-b
def multiply(a,b):
&&& print"Multiplying%d*%d"%(a,b)
&&& return a*b
def divide(a,b):
&&& print"Dividing%d/%d"%(a,b)
&&& return a/b
print"let‘s do some math with just functions!"&&&
age=add(30,5)
height=subtract(78,4)
weight=multiply(90,2)
iq=divide(100,2)
print"Age: %d, Height: %d, Weight: %d, IQ: %d"%(age,height,weight,iq)
#A puzzle for the extra credit, type it in anyway.
print"Here is a puzzle."
what = add(age,subtract(height,multiply(weight,divide(iq,2))))
print "That becomes:", what, "Can you do it by hand?"
#coding=utf-8
print"Let‘s practice everything."
print"You\‘d neen to know \‘bout escape with \\ theat do \n newlines and \t tabs"
\t The lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intution
and requires an explanation
\n\twhere there is none.
print"------"
print poem
print"------"
five = 10-2+3-6
print"This should be five:%s"% five
def secret_formula(started):
&&& jelly_beans=started * 500
&&& jars=jelly_beans / 1000
&&& crates=jars / 100
&&& return jelly_beans, jars, crates
start_point=10000
beans, jars, crates = secret_formula(start_point)&&&
print "With a starting point of: %d" % start_point
print "We‘d have %d beans, %d jars, and %d crates."% (beans, jars, crates)
start_point = start_point /10
print "We can also do that this way:"
print "We‘d have %d beans, %d jars, and %d crates."% secret_formula(start_point)
#函数return的几个值都可以用作结格式数据里面里面
Ec25自己写函数作为脚本,文档注释
#coding=utf-8
def break_words(stuff):
&&& ‘‘‘This function will break up words for us.‘‘‘
#这些东西是放在‘‘‘之间的,文档注解,documentation commnets,大型项目可供查阅!
# 如何查阅?python -m pydoc ec25
&&& words = stuff.split(‘ ‘)
&&& return words
def sort_words(words):
&&& """Sorts the words."""
&&& return sorted(words)#对单个词进行排序
def print_first_word(words):
&&& """Prints the first word after popping if off."""
&&& word =words.pop(0)
&&& print word
def print_last_word(words):
&&& """Prints the last word after popping if off."""
&&& word =words.pop(-1)
&&& print word
def sort_sentence(sentence):
&&& """Takes in a full sentence and returns the sorted words."""
&&& words = break_words(sentence)
&&& return sort_words(words)#句子排序,先拆分词。
def print_first_and_last(sentence):
&&& """Prints the first and last words of the sentence."""
&&& words=break_words(sentence)
&&& print_first_word(words)
&&& print_last_word(words)
def print_first_and_last_sorted(sentence):
&&& """Sorts the words then prints the first and last one."""
&&& words=sort_sentence(sentence)
&&& print_first_word(words)
&&& print_last_word(words)
#这一节学完,知道可以以后自己写函数作为脚本,然后不停的import就行,
# 注意函数之间写文档注释,这个也很屌。
Ec31 if & raw_input()
#coding=utf-8
print"You enter a dark room with two doors. "
print"Do you go through door #1 or door #2?"
door =raw_input("&&&&&&")
if door == "1":
&&& print"There‘s a giant bear here eating a cheese cake. What do you do?"
&&& print"1. Take the cake."
&&& print"2. Scream at the bear."
&&& bear = raw_input("&&&&&&")
&&& if bear == "1":
&&&&&&& print"The bear eats your face off. Good job!"
&&& elif bear == "2":
&&&&&&& print"The bear eats your legs off. Good job!"
&&&&&&& print"Well, doing %s is probably better. Bear runs away."% bear
elif door == "2":
&&& print"You stare into the endless abyss at Cthulhu‘s retina."
&&& print"1. Blueberries.\n2. Yellow jacket clothespins."
&&& print"3. Understanding revolvers yelling melodies."
&&& insanity = raw_input("&&&&&&")
&&& if insanity == "1" or insanity =="2":
&&&&&&& print"Your body survies powered by a mind of jello. Good job!"
&&&&&&& print"The insanity rots your eyes into a pool of muck. Good job!"
else:&&&&&&&
&&& print"Your stumble around and fall on a knife and die. Good job!"
#coding=utf-8
numbers=[]
while i&6:
&&& print"At the top i is %d"% i
&&& numbers.append(i)
&&& print"Numbers Now:",numbers
&&& print"At the bottom i is %d" % i
print"The numbers:"
for num in numbers:
&&& print num
ec35用函数写的一个小的选择游戏
#coding=utf-8
from sys import exit
def gold_room():
&&& print"This room is full of gold. How much do you take?"
&&& next =raw_input("&~&")
&&& if "0" in next or "1" in next:#判断输入是否有0或1,要包含所有的数字
&&&&&&& how_much = int(next)
&&&&&&& dead("Man, learn to type a number.")
&&& if how_much & 50:
&&&&&&& print"Nice, you‘re not greedy, you win!"
&&&&&&& exit()
&&&&&&& dead("You greedy bastard!")
def bear_room():
&&& print"There is a bear here."
&&& print"The bear has a bunch of honey."
&&& print"The fat bear is in front of another door."
&&& print"How are you going to move the bear?"
&&& bear_moved=False
&&& while True:
&&&&&&& next =raw_input("&~&")
&&&&&&& if next == "take honey":
&&&&&&&&&&& dead("The bear looks at you then slaps your face off.")
&&&&&&& elif next == "taunt bear" and not bear_moved:
&&&&&&&&&&& print"The bear has moved from the door. You can go through it now."
&&&&&&&&&&& bear_moved=True
&&&&&&& elif next == "taunt bear" and bear_moved:
&&&&&&&&&&& dead("The bear gets pissed off and chews your leg off.")
&&&&&&& elif next == "open door" and bear_moved:
&&&&&&&&&&& gold_room()
&&&&&&& else:
&&&&&&&&&&& print"I got no idea what that means."
def cthulhu_room():
&&& print"Here you see the great evil Cthulhu."
&&& print"He, it, whatever stares at you and you go insane."
&&& print"Do you flee for your life or eat your head?"
&&& next = raw_input("&~&")
&&& if "flee" in next:
&&&&&&& start()#这边就起到回调的作用,游戏中的返回。。。很好用啊
&&& elif "head" in next:
&&&&&&& dead("Well that was tasty!")
&&&&&&& cthulhu_room()
def dead(why)&&&&&&& :
&&& print why, "Good job!"
&&& exit(0)
def start():
&&& ‘‘‘Game start from here!‘‘‘
&&& print"You are in a dark room."
&&& print"There is a door to your right and left."&&&
&&& print"which one do you take?"
&&& next = raw_input("&~&")
&&& if next == "left":
&&&&&&& bear_room()
&&& elif next =="right":
&&&&&&& cthulhu_room()
&&&&&&& dead("You stumble around the room until you starve.")
start()&&&&&&&
ec39列表的操作
#coding=utf-8
ten_things="Apples Oranges Crows Telephone Light Sugar"
print"Wait there‘s not 10 things in that list,let‘s fix that."
stuff = ten_things.split(‘ ‘)
more_stuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]
print "stuff is %r\nand it‘s lens is %d"% (stuff,len(stuff))
while len(stuff) != 10:
&&& next_one = more_stuff.pop()#从more_stuff的最后一项挑出来放到stuff中
&&& print "Adding:", next_one
&&& stuff.append(next_one)#这种用法非常适合两个List之间互换
&&& print "There‘s %d items now."% len(stuff)
print"there we go: ",stuff
print"Let‘s do some things with stuff."&&&
print stuff[1]
print stuff[-1]
print stuff.pop()
print ‘&&‘.join(stuff)#join的用法
print ‘#‘.join(stuff[3:6])#下限是不包含的
#coding=utf-8
stuff={1:"dahu",2:"daqing",3:"tech"}
#print stuff[2]
stuff[‘city‘]=‘jianhu‘
#print stuff[‘city‘]
stuff[55]=2
#print stuff
cities={"CA": ‘San Francisco‘, "MI": ‘Detroit‘, "FL": ‘Jacksonville‘}
cities["NY"]="New York"
cities["OR"]="Portland"
def find_city(themap, state):
&&& if state in themap:
&&&&&&& return themap[state]
&&&&&&& return"Not found."
#OK pay attention!
# cities["_find"]=find_city#函数也可以作为一个变量
while True:
&&& print "State?(Enter to quit)",
&&& state = raw_input("&&&")
&&& if not state:break
&&& #this line is the most important
&&& # city_found=cities["_find"](cities,state)
&&& #这个运行时会在字典里建立_find键,其实没必要
&&& city_found=find_city(cities,state)
&&& print city_found
&&& print cities
map 函数应用
def add100(x):
&&& return x+100
hh=[11,22,33]
a=map(add100,hh)&&&
print "a is " ,a
def abc(a,b,c):
&&& return a*10000+b*100+c
list1=[11,22,33]&&&
list2=[44,55,66]
list3=[77,88,99]
b=map(abc,list1,list2,list3)
c=map(None,list1)
d=map(None,list1,list2,list3)
ec41函数写小型地图游戏,raw_input提示给答案
#coding=utf-8
from sys import exit
from random import randint
def death():
&&& quips = ["You died. You kinda suck at this.",
&&&&&&&&&&&& "Nice job, you died ...jackass.",
&&&&&&&&&&&& "Such a loser.",
&&&&&&&&&&&& "I have a small puppy that‘s better at this."]
&&& print quips[randint(0,len(quips)-1)]
&&& exit()
def central_corridor():
&&& print"The Gothons of Planet Percal #25 have invaded your ship and destroyed"
&&& print"your entire crew. You are the last surviving member and your last"
&&& print"mission is to get the neutron destruct bomb from the Weapons Armory,"
&&& print"put it in the bridge, and blow the ship up after getting into an"
&&& print"escape pod.\n"
&&& print"You‘re running down the central corridor to the Weapons Armory when"
&&& print"a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
&&& print"flowing around his hate filled body. He‘s blocking the door to the"
&&& print"Armory and about to pull a weapon to blast you."
&&& action=raw_input(‘‘‘\nI‘l give you some advice&&
&&& \n shoot!\t dodge!\t tell a joke\t\n&&‘‘‘)
&&& if action == "shoot!":
&&&&&&& print "Quick on the draw you yank out your blaster and fire it at the Gothon."
&&&&&&& print "His clown costume is flowing and moving around his body, which throws"
&&&&&&& print "off your aim. Your laser hits his costume but misses him entirely. This"
&&&&&&& print "completely ruins his brand new costume his mother bought him, which"
&&&&&&& print "makes him fly into an insane rage and blast you repeatedly in the face until"
&&&&&&& print "you are dead. Then he eats you."
&&&&&&& return ‘death‘
&&& elif action == "dodge!":
&&&&&&& print "Like a world class boxer you dodge, weave, slip and slide right"
&&&&&&& print "as the Gothon‘s blaster cranks a laser past your head."
&&&&&&& print "In the middle of your artful dodge your foot slips and you"
&&&&&&& print "bang your head on the metal wall and pass out."
&&&&&&& print "You wake up shortly after only to die as the Gothon stomps on"
&&&&&&& print "your head and eats you."
&&&&&&& return ‘death‘
&&& elif action == "tell a joke":
&&&&&&& print "Lucky for you they made you learn Gothon insults in the academy."
&&&&&&& print "You tell the one Gothon joke you know:"
&&&&&&& print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
&&&&&&& print "The Gothon stops, tries not to laugh, then busts out laughing and can‘t move."
&&&&&&& print "While he‘s laughing you run up and shoot him square in the head"
&&&&&&& print "putting him down, then jump through the Weapon Armory door."
&&&&&&& return ‘laser_weapon_armory‘
&&&&&&& print "DOES NOT COMPUTE!"
&&&&&&& return ‘central_corridor‘
def laser_weapon_armory():
&&& print "You do a dive roll into the Weapon Armory, crouch and scan the room"
&&& print "for more Gothons that might be hiding. It‘s dead quiet, too quiet."
&&& print "You stand up and run to the far side of the room and find the"
&&& print "neutron bomb in its container. There‘s a keypad lock on the box"
&&& print "and you need the code to get the bomb out. If you get the code"
&&& print "wrong 10 times then the lock closes forever and you can‘t"
&&& print "get the bomb. The code is 3 digits."
&&& code = "%d%d%d" %(randint(1,9),randint(1,9),randint(1,9))
&&& print"Code is %s" % code
&&& guess=raw_input("[keypad]& ")
&&& guesses=0
&&& while guess != code and guesses &10:
&&&&&&& print "BZZZEDD!"
&&&&&&& guesses +=1
&&&&&&& guess =raw_input("[keypad]& ")
&&& if guess == code:
&&&&&&& print "The container clicks open and the seal breaks, letting gas out."
&&&&&&& print "You grab the neutron bomb and run as fast as you can to the"
&&&&&&& print "bridge where you must place it in the right spot."
&&&&&&& return ‘the_bridge‘
&&&&&&& print "The lock buzzes one last time and then you hear a sickening"
&&&&&&& print "melting sound as the mechanism is fused together."
&&&&&&& print "You decide to sit there, and finally the Gothons blow up the"
&&&&&&& print "ship from their ship and you die."
&&&&&&& return ‘death‘
def the_bridge():
&&& print "You burst onto the Bridge with the neutron destruct bomb"
&&& print "under your arm and surprise 5 Gothons who are trying to"
&&& print "take control of the ship. Each of them has an even uglier"
&&& print "clown costume than the last. They haven‘t pulled their"
&& &print "weapons out yet, as they see the active bomb under your"
&&& print "arm and don‘t want to set it off."
&&& action=raw_input(‘‘‘\nI‘l give you some advice&&
&&& \n throw the bomb\t slowly place the bomb\t\n&&‘‘‘)
&&& if action == "throw the bomb":
&&&&&&& print "In a panic you throw the bomb at the group of Gothons"
&&&&&&& print "and make a leap for the door. Right as you drop it a"
&&&&&&& print "Gothon shoots you right in the back killing you."
&&&&&&& print "As you die you see another Gothon frantically try to disarm"
&&&&&&& print "the bomb. You die knowing they will probably blow up when"
&&&&&&& print "it goes off."
&&&&&&& return ‘death‘
&&& elif action == "slowly place the bomb":
&&&& &&&print "You point your blaster at the bomb under your arm"
&&&&&&& print "and the Gothons put their hands up and start to sweat."
&&&&&&& print "You inch backward to the door, open it, and then carefully"
&&&&&&& print "place the bomb on the floor, pointing your blaster at it."
&&&&&&& print "You then jump back through the door, punch the close button"
&&&&&&& print "and blast the lock so the Gothons can‘t get out."
&&&&&&& print "Now that the bomb is placed you run to the escape pod to"
&&&&&&& print "get off this tin can."
&&&&&&& return ‘escape_pod‘
&&&&&&& print "DOES NOT COMPUTE!"
&&&&&&& return "the_bridge"
def escape_pod():
&&& print "You rush through the ship desperately trying to make it to"
&&& print "the escape pod before the whole ship explodes. It seems like"
&&& print "hardly any Gothons are on the ship, so your run is clear of"
&&& print "interference. You get to the chamber with the escape pods, and"
&&& print "now need to pick one to take. Some of them could be damaged"
&&& print "but you don‘t have time to look. There‘s 5 pods, which one"
&&& print "do you take?"
&&& good_pod = randint(1,5)
&&& print "good_pod is %d" % good_pod
&&& guess = raw_input("[pod #]& ")
&&& if int(guess) !=good_pod:
&&&&&&& print "You jump into pod %s and hit the eject button." % guess
&&&&&&& print "The pod escapes out into the void of space, then"
&&&&&&& print "implodes as the hull ruptures, crushing your body"
&&&&&&& print "into jam jelly."
&&&&&&& return ‘death‘
&&&&&&& print "You jump into pod %s and hit the eject button." % guess
&&&&&&& print "The pod easily slides out into space heading to"
&&&&&&& print "the planet below. As it flies to the planet, you look"
&&&&&&& print "back and see your ship implode then explode like a"
&&&&&&& print "bright star, taking out the Gothon ship at the same"
&&&&&&& print "time. You won!"
&&&&&&& exit(0)
&&& ‘death‘: death,
&&& ‘central_corridor‘:central_corridor,
&&& ‘laser_weapon_armory‘:laser_weapon_armory,
&&& ‘the_bridge‘:the_bridge,
&&& ‘escape_pod‘:escape_pod}
def runner(map, start):
&&& next = start
&&& while True:
&&&&&&& room = map[next]
&&&&&&& print "\n------"
&&&&&&& next = room() #这句话操作层面算是理解了,
&&&&&&& # 但是按顺序应该在---的后面,但在powersheel中出现在前面,这是为什么
&&&&&&& print"&&next&&",next
runner(Rooms,‘central_corridor‘)&&&&&&&
ec随机数用法
#coding=utf-8
from sys import exit
from random import randint
def death():
&&& quips = ["You died. You kinda suck at this.",
&&&& &&&&&&&&"Nice job, you died ...jackass.",
&&&&&&&&&&&& "Such a loser.",
&&&&&&&&&&&& "I have a small puppy that‘s better at this."]
&&& # print len(quips)-1
&&& a= randint(0,3) #取随机数的两端都可以取到!
&&& print a
&&& print quips[a]
&&& exit()
getattr用法
#coding=utf-8
class A:&&
&&& def __init__(self):&&
&&&&&&& self.name = ‘zhangjing‘&
&&&&&&& self.age=‘24‘
&&& def method(self):&&
&&&&&&& print"method print"&
Instance = A()&&
print getattr(Instance , ‘name‘) #如果Instance 对象中有属性name则打印self.name的值,否则打印‘not find‘
print getattr(Instance , ‘age‘)&& #如果Instance 对象中有属性age则打印self.age的值,否则打印‘not find‘
print getattr(Instance, ‘method‘, ‘default‘)&&
#如果有方法method,打印其地址,否则打印default&&
print getattr(Instance, ‘method‘, ‘default‘)()&&
#如果有方法method,运行函数并打印None否则打印default&&
Ec42class写ec41的游戏
#coding=utf-8
from sys import exit
from random import randint
class Game(object):
&&& def __init__(self,start):
&&&&&&& self.quips=["You died. You kinda suck at this.",
&&&&&&&&&&& "Nice job, you died ...jackass.",
&&&&&& &&&&&"Such a loser.",
&&&&&&&&&&& "I have a small puppy that‘s better at this."
&&&&&&& self.start = start
&&& def play(self):
&&&&&&& next =self.start
&&&&&&& while True:
&&&&&&&&&&& print"\n-----"
&&&&&&&&&&& room = getattr(self,next)&&&&&&&&&&
&&&&&&&&&&& next = room()
&&&&&&&&&&&
&&& def death(self):
&&&&&&& print self.quips[randint(0,len(self.quips)-1)]
&&&&&&& exit()
&&& def central_corridor(self):
&&&&&&& print"The Gothons of Planet Percal #25 have invaded your ship and destroyed"
&&&&&&& print"your entire crew. You are the last surviving member and your last"
&&&&&&& print"mission is to get the neutron destruct bomb from the Weapons Armory,"
&&&&&&& print"put it in the bridge, and blow the ship up after getting into an"
&&&&&&& print"escape pod.\n"
&&&&&&& print"You‘re running down the central corridor to the Weapons Armory when"
&&&&&&& print"a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
&&&&&&& print"flowing around his hate filled body. He‘s blocking the door to the"
&&&&&&& print"Armory and about to pull a weapon to blast you."
&&&&&&& action=raw_input(‘‘‘\nI‘l give you some advice&&
&&&&&&& \n shoot!\t dodge!\t tell a joke\t\n&&‘‘‘)
&&&&&&& if action == "shoot!":
&&&&&&&&&&& print "Quick on the draw you yank out your blaster and fire it at the Gothon."
&&&&&&&&&&& print "His clown costume is flowing and moving around his body, which throws"
&&&&&&&&&&& print "off your aim. Your laser hits his costume but misses him entirely. This"
&&&&&&&&&&& print "completely ruins his brand new costume his mother bought him, which"
&&&&&&&&&&& print "makes him fly into an insane rage and blast you repeatedly in the face until"
&&&&&&&&&&& print "you are dead. Then he eats you."
&&&&&&&&&&& return ‘death‘
&&&&&&& elif action == "dodge!":
&&&&&&&&&&& print "Like a world class boxer you dodge, weave, slip and slide right"
&&&&&&&&&&& print "as the Gothon‘s blaster cranks a laser past your head."
&&&&&&&&&&& print "In the middle of your artful dodge your foot slips and you"
&&&&&&&&&&& print "bang your head on the metal wall and pass out."
&&&&&&&&&&& print "You wake up shortly after only to die as the Gothon stomps on"
&&&&&&&&&&& print "your head and eats you."
&&&&&&&&&&& return ‘death‘
&&&&&&& elif action == "tell a joke":
&&&&&&&&&&& print "Lucky for you they made you learn Gothon insults in the academy."
&&&&&&&&&&& print "You tell the one Gothon joke you know:"
&&&&&&&&&&& print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
&&&&&&&&&&& print "The Gothon stops, tries not to laugh, then busts out laughing and can‘t move."
&&&&&&&&&&& print "While he‘s laughing you run up and shoot him square in the head"
&&&&&&&&&&& print "putting him down, then jump through the Weapon Armory door."
&&&&&&&&&&& return ‘laser_weapon_armory‘
&&&&&&&&&&&
&&&&&&& else:
&&&&&&&&&&& print "DOES NOT COMPUTE!"
&&&&&&&&&&& return ‘central_corridor‘
&&& def laser_weapon_armory(self):
&&&&&&& print "You do a dive roll into the Weapon Armory, crouch and scan the room"
&&&&&&& print "for more Gothons that might be hiding. It‘s dead quiet, too quiet."
&&&&&&& print "You stand up and run to the far side of the room and find the"
&&&&&&& print "neutron bomb in its container. There‘s a keypad lock on the box"
&&&&&&& print "and you need the code to get the bomb out. If you get the code"
&&&&&&& print "wrong 10 times then the lock closes forever and you can‘t"
&&&&&&& print "get the bomb. The code is 3 digits."
&&&&&&& code = "%d%d%d" %(randint(1,9),randint(1,9),randint(1,9))
&&&&&&& print"Code is %s" % code
&&&&&&& guess=raw_input("[keypad]& ")
&&&&&&& guesses=0
&&&&&&& while guess != code and guesses &10:
&&&&&&&&&&& print "BZZZEDD!"
&&&&&&&&&&& guesses +=1
&&&&&&&&&&& guess =raw_input("[keypad]& ")
&&&&&&& if guess == code:
&&&&&&&&&&& print "The container clicks open and the seal breaks, letting gas out."
&&&&&&&&&&& print "You grab the neutron bomb and run as fast as you can to the"
&&&&&&&&&&& print "bridge where you must place it in the right spot."
&&&&&&&&&&& return ‘the_bridge‘
&&&&&&& else:
&&&&&&&&&&& print "The lock buzzes one last time and then you hear a sickening"
&&&&&&&&&&& print "melting sound as the mechanism is fused together."
&&&&&&&&&&& print "You decide to sit there, and finally the Gothons blow up the"
&&&&&&&&&&& print "ship from their ship and you die."
&&&&&&&&&&& return ‘death‘
&&&&&&&&&&&
&&& def the_bridge(self):
&&&&&&& print "You burst onto the Bridge with the neutron destruct bomb"
&&&&&&& print "under your arm and surprise 5 Gothons who are trying to"
&&&&&&& print "take control of the ship. Each of them has an even uglier"
&&&&&&& print "clown costume than the last. They haven‘t pulled their"
&&&&&&& print "weapons out yet, as they see the active bomb under your"
&&&&&&& print "arm and don‘t want to set it off."
&&&&&&& action=raw_input(‘‘‘\nI‘l give you some advice&&
&&&&&&& \n throw the bomb\n slowly place the bomb\t\n&&‘‘‘)
&&&&&&& if action == "throw the bomb":
&&&&&&&&&&& print "In a panic you throw the bomb at the group of Gothons"
&&&&&&&&&&& print "and make a leap for the door. Right as you drop it a"
&&&&&&&&&&& print "Gothon shoots you right in the back killing you."
&&&&&&&&&&& print "As you die you see another Gothon frantically try to disarm"
&&&&&&&&&&& print "the bomb. You die knowing they will probably blow up when"
&&&&&&&&&&& print "it goes off."
&&&&&&&&&&& return ‘death‘
&&&&&&& elif action == "slowly place the bomb":
&&&&&&&&&&& print "You point your blaster at the bomb under your arm"
&&&&&&&&&&& print "and the Gothons put their hands up and start to sweat."
&&&&&&&&&&& print "You inch backward to the door, open it, and then carefully"
&&&&&&&&&&& print "place the bomb on the floor, pointing your blaster at it."
&&&&&&&&&&& print "You then jump back through the door, punch the close button"
&&&&&&&&&&& print "and blast the lock so the Gothons can‘t get out."
&&&&&&&&&&& print "Now that the bomb is placed you run to the escape pod to"
&&&&&&&&&&& print "get off this tin can."
&&&&&&&&&&& return ‘escape_pod‘
&&&&&&& else:
&&&&&&&&&&& print "DOES NOT COMPUTE!"
&&&&&&&&&&& return "the_bridge"&&
&&&&&&&&&&&
&&& def escape_pod(self):
&&&&&&& print "You rush through the ship desperately trying to make it to"
&&&&&&& print "the escape pod before the whole ship explodes. It seems like"
&&&&&&& print "hardly any Gothons are on the ship, so your run is clear of"
&&&&&&& print "interference. You get to the chamber with the escape pods, and"
&&&&&&& print "now need to pick one to take. Some of them could be damaged"
&&&&&&& print "but you don‘t have time to look. There‘s 5 pods, which one"
&&&&&&& print "do you take?"
&&&&&&& good_pod = randint(1,5)
&&&&&&& print "good_pod is %d" % good_pod
&&&&&&& guess = raw_input("[pod #]& ")
&&&&&&& if int(guess) !=good_pod:
&&&&&&&&&&& print "You jump into pod %s and hit the eject button." % guess
&&&&&&&&&&& print "The pod escapes out into the void of space, then"
&&&&&&&&&&& print "implodes as the hull ruptures, crushing your body"
&&&&&&&&&&& print "into jam jelly."
&&&&&&&&&&& return ‘death‘
&&&& &&&else:
&&&&&&&&&&& print "You jump into pod %s and hit the eject button." % guess
&&&&&&&&&&& print "The pod easily slides out into space heading to"
&&&&&&&&&&& print "the planet below. As it flies to the planet, you look"
&&&&&&&&&&& print "back and see your ship implode then explode like a"
&&&&&&&&&&& print "bright star, taking out the Gothon ship at the same"
&&&&&&&&&&& print "time. You won!"
&&&&&&&&&&& exit(0)
&&&&&&&&&&&
a_game = Game("central_corridor")&&
a_game.play()
ec处理异常try & except
#coding=utf-8
def convert_number(s):
&&&&&&& return int(s)
&&& except ValueError:
&&&&&&& return None
s=raw_input("PLZ&&")&&&&&&&
print(convert_number(s))
From实验楼
Pathbao.py
#coding=utf-8
import os.path
path=‘H:\python_program\shiyanlou\saile.txt‘
print(os.path.basename(path))
print(os.path.dirname(path))
info = os.path.split(path)
path2=os.path.join(‘/‘,‘python_program‘,‘shiyanlou‘,‘saile.txt‘)
print path2
# 这里的斜杠注意下,win7里面是"\",而实验楼里面的是"/",这个影响大不大
a=‘H:\python_program\shiyanlou\..‘
# print(os.path.normpath(a))
print"path is %r" % path
print(‘exit?‘,os.path.exists(path))
print(‘size?‘,os.path.getsize(path))
print(‘last read time?‘,os.path.getatime(path))
print(‘last edit time?‘,os.path.getmtime(path))
print(‘path to file?‘,os.path.isfile(path))
print(‘path to dir?‘,os.path.isdir(path))
#coding=utf-8
import glob
print(glob.glob("H:\python_program\shiyanlou\*"))
#该命令找出文件夹下所有文件。
#coding=utf-8
path=‘H:\python_program\shiyanlou\wc‘
#这里需要注意下,用mkdir创建文件目录时,最后一个不用\
# os.mkdir(path)#创建新目录
# os.rmdir(path)#删除空目录
# a=os.listdir(path)#返回目录中所有文件。相当于$ls命令,存起来
# path=‘H:\python_program\shiyanlou\wc\saile.txt‘
# os.remove(path)#删除 path指向的文件。path指向某个文件,注意文件名与\的作用。
# path1=‘H:\python_program\shiyanlou\wc2\saile.txt‘
# path2=‘H:\python_program\shiyanlou\wc2\what.txt‘
# os.rename(path1, path2)
#重命名文件,src和ds为两个路径,分别表示重命名之前和之后的路径。
#重命名后,path1消失了,path2产生了,就是重命名文件夹,试试重命名文件,文件也是可以的。
print(os.getcwd())#查询当前工作路径
#coding=utf-8
import shutil
print(os.getcwd())
shutil.copy(‘a.txt‘,‘b.txt‘)
# copy(src, dst) 复制文件,从src到dst。相当于$cp命令。
# move(src, dst) 移动文件,从src到dst。相当于$mv命令。
#运用此命令需要先确定文件的位置,一开始确定工作区也是可行的!
#coding=utf-8
import pickle
class Bird(object):
&&& have_feather=True
&&& way_of_reproduction = ‘egg‘
summer = Bird()
picklestring = pickle.dumps(summer)&&&
print picklestring
#coding=utf-8
import pickle
class Bird(object):
&&& have_feather = True
&&& way_of_reproduction = ‘egg‘
summer = Bird()
fn = ‘a.pkl‘&&&
with open(fn,‘w‘) as f:
&&& picklestring = pickle.dump(summer, f)
print picklestring&&&
#这个最后结果是none,不知哪里wrong
print summer
#是放在summer里面的。握草,那为什么picklestring 里面是none?
#coding=utf-8
import pickle
class Bird(object):
&&& have_feather = True
&&& way_of_reproduction = ‘egg‘
fn =‘a.pkl‘
with open(fn,‘r‘) as f:
&&& summer = pickle.load(f)
print summer&&&
subprocess包
import subprocess
child =subprocess.Popen(["ping","www.baidu.com"])
# child.wait()
print"parent process"
import subprocess
out=subprocess.call("ls -l",shell=True)
out=subprocess.call("cd ..",shell=True)
import subprocess
child1 = subprocess.Popen(["print","abcd"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE)
out = child2.communicate()
print(out)
#coding=utf-8
# A program to simulate selling tickets in multi-thread way
# Written by Vamei
import threading
import time
# This function could be any function to do other chores.
def doChore():
&&& time.sleep(0.2)
# Function for each thread
def booth(tid):
&&& global i
&&& global lock
&&& while True:
&&&&&&& lock.acquire()&&&&&&&&&&&&&&& # L or wait if other thread is holding the lock
&&&&&&& if i != 0:
&&&&&&&&&&& i = i - 1&&&&&&&&&&&&&&&& # Sell tickets
&&&&&&&&&&& print(tid,‘:now left:‘,i) # Tickets left
&&&&&&&&&&& doChore()&&&&&&&&&&&&&&&& # Other critical operations
&&&&&&& else:
&&&&&&&&&&& print("Thread_id",tid," No more tickets")
&&&&&&&&&&& os._exit(0)&&&&&&&&&&&&& # Exit the whole process immediately
&&&&&&& lock.release()&&&&&&&&&&&&&& # Unblock
&&&&&&& doChore()&&&&&&&&&&&&&&&&&&& # Non-critical operations
# Start of the main function
i&&& = 100&&&&&&&&&&&&&&&&&&&&&&&&&& # Available ticket number
lock = threading.Lock()&&&&&&&&&&&&& # Lock (i.e., mutex)
# Start 10 threads
for k in range(10):
&&& new_thread = threading.Thread(target=booth,args=(k,))&& # S target: the callable (function) to be run, args: the argument for the callable
new_thread.start()&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& # run the thread
import threading
import time
# This function could be any function to do other chores.
def doChore():
&&& time.sleep(0.5)
# Function for each thread
class BoothThread(threading.Thread):
&&& def __init__(self, tid, monitor):
&&&&&&& self.tid&&&&&&&&& = tid
&&&&&&& self.monitor = monitor
&&&&&&& threading.Thread.__init__(self)
&&& def run(self):
&&&&&&& while True:
&&&&&&&&&&& monitor[‘lock‘].acquire()&&&&&&&&&&&&&&&&&&&&&&&&& # L or wait if other thread is holding the lock
&&&&&&&&&&& if monitor[‘tick‘] != 0:
&&&&&&&&&&&&&&& monitor[‘tick‘] = monitor[‘tick‘] - 1&&&&&&&&& # Sell tickets
&&&&&&&&&&&&&&& print(self.tid,‘:now left:‘,monitor[‘tick‘])&& # Tickets left
&&&&&&&&&&&&&&& doChore()&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& # Other critical operations
&&&&&&&&&&& else:
&&&&&&&&&&&&&&& print("Thread_id",self.tid," No more tickets")
&&&&&&&&&&&&&&& os._exit(0)&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&# Exit the whole process immediately
&&&&&&&&&&& monitor[‘lock‘].release()&&&&&&&&&&&&&&&&&&&&&&&&& # Unblock
&&&&&&&&&&& doChore()&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& # Non-critical operations
# Start of the main function
monitor = {‘tick‘:100, ‘lock‘:threading.Lock()}
# Start 10 threads
for k in range(10):
&&& new_thread = BoothThread(k, monitor)
new_thread.start()
multiprocessing包
import multiprocessing as mul
def proc1(pipe):
&&& pipe.send(‘hello‘)
&&& print(‘proc1 rec:‘,pipe.recv())
def proc2(pipe):
&&& print(‘proc2 rec:‘,pipe.recv())
&&& pipe.send(‘hello, too‘)
# Build a pipe
pipe = mul.Pipe()
# Pass an end of the pipe to process 1
p1&& = mul.Process(target=proc1, args=(pipe[0],))
# Pass the other end of the pipe to process 2
p2&& = mul.Process(target=proc2, args=(pipe[1],))
p1.start()
p2.start()
#coding=gbk
s = "中文"
s1 = u"中文"
s2 = unicode(s, "gbk") #省略参数将用python默认的ASCII来解码
s3 = s.decode("gbk") #把str转换成unicode是decode,unicode函数作用与之相同
print len(s)
print len(s1)
print len(s2)
print len(s3)
import codecs
# print open("file.txt").read().decode("utf-8")
print open("file.txt").read()
#文本类型的文件读取,在utf-8和ANSI编码之间的切换。
Sy6.py线程实验售票系统
#coding=utf-8
# A program to simulate selling tickets in multi-thread way
# Written by Vamei
import threading
import time
# This function could be any function to do other chores.
def doChore():
&&& time.sleep(0.01)#这边可以用来调节时间,快慢
# Function for each thread
def booth(tid):
&&& global i
&&& global lock
&&& while True:
&&&&&&& lock.acquire()&&&&&&&&&&&&&&& # L or wait if other thread is holding the lock
&&&&&&& if i != 0:
&&&&&&&&&&& i = i - 1&&&&&&&&&&&&&&&& # Sell tickets
&&&&&&&&&&& print(tid,‘:now left:‘,i) # Tickets left
&&&&&&&&&&& doChore()&&& &&&&&&&&&&&&&# Other critical operations
&&&&&&& else:
&&&&&&&&&&& print("Thread_id",tid," No more tickets")
&&&&&&&&&&& os._exit(0)&&&&&&&&&&&&& # Exit the whole process immediately
&&&&&&& lock.release()&&&&&&&&&&&&&& # Unblock
&&&&&&& doChore()&&&&&&&& &&&&&&&&&&&# Non-critical operations
# Start of the main function
i&&& = 100&&&&&&&&&&&&&&&&&&&&&&&&&& # Available ticket number
lock = threading.Lock()&&&&&&&&&&&&& # Lock (i.e., mutex)
# Start 10 threads
for k in range(10):
&&& new_thread = threading.Thread(target=booth,args=(k,))&& # S target: the callable (function) to be run, args: the argument for the callable
&&& new_thread.start()&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& # run the thread
sy6.py用类实现
import threading
import time
# This function could be any function to do other chores.
def doChore():
&&& time.sleep(0.5)
# Function for each thread
class BoothThread(threading.Thread):
&&& def __init__(self, tid, monitor):
&&&&&&& self.tid&&&&&&&&& = tid
&&&&&&& self.monitor = monitor
&&&&&&& threading.Thread.__init__(self)
&&& def run(self):
&&&&&&& while True:
&&&&&&&&&&& monitor[‘lock‘].acquire()&&&&&&&&&&&&&&&&&&&&&&&&& # L or wait if other thread is holding the lock
&&&&&&&&&&& if monitor[‘tick‘] != 0:
&&&&&&&&&&&&&&& monitor[‘tick‘] = monitor[‘tick‘] - 1&&&&&&&&& # Sell tickets
&&&&&&&&&&&&&&& print(self.tid,‘:now left:‘,monitor[‘tick‘])&& # Tickets left
&&&&&&&&&&&&&&& doChore()&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& # Other critical operations
&&&&&&&&&&& else:
&&&&&&&& &&&&&&&print("Thread_id",self.tid," No more tickets")
&&&&&&&&&&&&&&& os._exit(0)&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& # Exit the whole process immediately
&&&&&&&&&&& monitor[‘lock‘].release()&&&&&&&&&&&&&&&&&&&&&&&&& # Unblock
&&&&&&&&&&& doChore()&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&# Non-critical operations
# Start of the main function
monitor = {‘tick‘:100, ‘lock‘:threading.Lock()}
# Start 10 threads
for k in range(10):
&&& new_thread = BoothThread(k, monitor)
&&& new_thread.start()
ascii.py argparse操作分解
#coding=utf-8
from PIL import Image
import argparse
ascii_char = list("%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~&&i!lI;:,\"^`‘. ")#字符全放在表里面,注意他们的使用方式
# print ascii_char
# print len(ascii_char)
# a=list("#$%")#fk,居然直接连起来就OK
def get_char(r,g,b,alpha = 256):#RGB值输进去,能转换成对应的字符编码
&&& if alpha == 0:
&&&&&&& return ‘ ‘
&&& length = len(ascii_char)
&&& gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
&&& unit = (256.0 + 1)/length
&&& return ascii_char[int(gray/unit)]
a=get_char(32,32,32,256)&&&
#~~~~~argparse部分学习
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo
#~~~~~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
&&& print "verbosity turned on"
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
&&&&&&&&&&&&&&&&&&& action="store_true")
args = parser.parse_args()
if args.verbose:
&& print "verbosity turned on"
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
&&&&&&&&&&&&&&&&&&& action="store_true")
args = parser.parse_args()
if args.verbose:
&&& print "verbosity turned on"
#~~~~~~~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
&&&&&&&&&&&&&&&&&&& help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
&&&&&&&&&&&&&&&&&&& help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbose:
&&& print "the square of {} equals {}".format(args.square, answer)
&&& print answer
这个例子有点大彻大悟的感觉啊,可以不停的加简写,多个参数就都输入,再试试别的,很好!
&&& $ python prog.py
usage: prog.py [-h] [-v] square
prog.py: error: the following arguments are required: square
$ python prog.py 4
$ python prog.py 4 --verbose
the square of 4 equals 16
$ python prog.py --verbose 4
the square of 4 equals 16‘‘‘
#~~~~~~~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
&&&&&&&&&&&&&&&&&&& help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
&&&&&&&&&&&&&&&&&&& help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
&&& print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
&&& print "{}^2 == {}".format(args.square, answer)
&&& print answer
‘‘‘运行:
$ python prog.py 4
$ python prog.py 4 -v
usage: prog.py [-h] [-v VERBOSITY] square
prog.py: error: argument -v/--verbosity: expected one argument
$ python prog.py 4 -v 1
4^2 == 16& 握草,这是给cerbosity赋值来操作啊,我就想到VBA里面各种参数的东西
$ python prog.py 4 -v 2
the square of 4 equals 16
$ python prog.py 4 -v 3
#~~~~~~~~~~~~~
# 除了最后一个暴露了一个bug,其他的看起都来运行良好。让我们通过限制--verbosity后面跟的值来修正:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
&&&&&&&&&&&&&&&&&&& help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
&&&&&&&&&&&&&&&&&&& help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
&&& print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
&&& print "{}^2 == {}".format(args.square, answer)
&&& print answer
$ python prog.py 4 -v 3
usage: prog.py [-h] [-v {0,1,2}] square
prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
$ python prog.py 4 -h
usage: prog.py [-h] [-v {0,1,2}] square
positional arguments:
& square&&&&&&&&&&&&&&& display a square of a given number
optional arguments:
& -h, --help&&&&&&&&&&& show this help message and exit
& -v {0,1,2}, --verbosity {0,1,2}
&&&&&&&&&&&&&&&&&&&&&&& increase output verbosity‘‘‘
#~~~~~~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
&&&&&&&&&&&&&&&&&&& help="display the square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
&&&&&&&&&&}

我要回帖

更多关于 java中yyyymmdd 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信