一些Python片段_4 & Python字符串格式化


用Google API抓取搜索结果
#!/usr/bin/env python
import urllib
import simplejson
query = urllib.urlencode({'q':'ixyzero.com'})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s'%(query)
search_results = urllib.urlopen(url)
json = simplejson.loads(search_results.read())
print(json)
results = json['responseData']['results']
print len(results)
for i in results:
    print i['title'] + ": " + i['url']
用Python生成随机密码
import string, random
def makePassword(minlength = 5, maxlength = 25):
    length = random.randint(minlength, maxlength)
    letters = string.ascii_letters + string.digits
    return ''.join([random.choice(letters) for _ in range(length)])
print makePassword()

print (sorted(random.sample(range(1,36), 5)) + sorted(random.sample(range(1,13),2)))
用Python生成随机密码_2
import random
class Dictor():
    CSet='abcdefghijklmnopqrstuvwxyz0123456789'
    def __init__(self, minlen, maxlen):
        if maxlen>minlen:
            self.__minlen=minlen
            self.__maxlen=maxlen
        else:
            self.__minlen=maxlen
            self.__maxlen=minlen
    def __iter__(self):
        return self
    def next(self):
        ret = ''
        for i in range(0, random.randrange(self.__minlen, self.__maxlen+1)):
            ret += random.choice(Dictor.CSet)
        return ret

for word in Dictor(3, 3):
    print str(word)
用Python生成中文验证码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
import random
import math, string

class RandomChar():
    """用于随机生成汉字"""
    @staticmethod
    def Unicode():
        val = random.randint(0x4E00, 0x9FBF)
        return unichr(val)

    @staticmethod
    def GB2312():
        head = random.randint(0xB0, 0xCF)
        body = random.randint(0xA, 0xF)
        tail = random.randint(0, 0xF)
        val = ( head << 8 ) | (body << 4) | tail
        str = "%x" % val
        return str.decode('hex').decode('gb2312')

class ImageChar():
    def __init__(self, fontColor = (0, 0, 0), size = (100, 40), fontPath = 'wqy.ttc', bgColor = (255, 255, 255), fontSize = 20):
        self.size = size
        self.fontPath = fontPath
        self.bgColor = bgColor
        self.fontSize = fontSize
        self.fontColor = fontColor
        self.font = ImageFont.truetype(self.fontPath, self.fontSize)
        self.image = Image.new('RGB', size, bgColor)

    def rotate(self):
        self.image.rotate(random.randint(0, 30), expand=0)

    def drawText(self, pos, txt, fill):
        draw = ImageDraw.Draw(self.image)
        draw.text(pos, txt, font=self.font, fill=fill)
        del draw

    def randRGB(self):
        return (random.randint(0, 255),
                random.randint(0, 255),
                random.randint(0, 255))

    def randPoint(self):
        (width, height) = self.size
        return (random.randint(0, width), random.randint(0, height))

    def randLine(self, num):
        draw = ImageDraw.Draw(self.image)
        for i in range(0, num):
            draw.line([self.randPoint(), self.randPoint()], self.randRGB())
        del draw

    def randChinese(self, num):
        gap = 5
        start = 0
        for i in range(0, num):
            char = RandomChar().GB2312()
            x = start + self.fontSize * i + random.randint(0, gap) + gap * i
            self.drawText((x, random.randint(-5, 5)), RandomChar().GB2312(), self.randRGB())
            self.rotate()
        self.randLine(18)

    def save(self, path):
        self.image.save(path)

ic = ImageChar(fontColor=(100,211, 90))
ic.randChinese(4)
ic.save("vcode.jpg")

安装PIL,并且引入方式为”from PIL import Image, ImageDraw, ImageFont”;然后去官网找文泉驿的字体,下载后存为”wqy.ttc”,之后应该就没多大问题了。

猜数字游戏
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random

#数字类
class NumberItem:

    #数字个数
    _GUESS_NUMBER_COUNT_ = 4

    def __init__(self):
        self._num_ = []

    #长度是否标准
    def IsFormat(self):
        return self._num_.__len__() == self._GUESS_NUMBER_COUNT_

    #生成随机数
    def RestRandomNumber(self):
        allNum = range(10)
        for index in range(self._GUESS_NUMBER_COUNT_):
            self._num_.append(allNum.pop(random.randrange(10-index)))

    #校验输入数
    def CheckNumber(self, input_number):
        result = NumberCheckResult()

        for index in range(self._GUESS_NUMBER_COUNT_):
            if (input_number._num_[index] == self._num_[index]):
                result.Add_A()
            elif(input_number._num_[index] in self._num_):
                result.Add_B()

        return result

    #返回字符串
    def GetNumber(self):
        return self._num_

#竞猜结果 xAxB
class NumberCheckResult:
    def __init__(self):
        self._guess_A_ = 0
        self._guess_B_ = 0

    def GetCheckResult(self):
        return '%d A %d B' % (self._guess_A_, self._guess_B_)

    def Add_A(self):
        self._guess_A_ += 1

    def Add_B(self):
        self._guess_B_ += 1

#竞猜历史项
class GuessHisItem:
    def __init__(self):
        self._guessNum_ = NumberItem()
        self._guessResult_ = NumberCheckResult()

    def ShowItem(self):
        print self._guessNum_.GetNumber() , ' - ' , self._guessResult_.GetCheckResult()

#游戏类
class GuessNumberGame():

    #机会次数
    _MAX_GUESS_TIMES_ = 8

    def __init__(self):
        self.ResetGameDate()

    #重置游戏数据
    def ResetGameDate(self):
        self._guessNum_ = NumberItem()
        self._guessHis_ = []

    def GetGuessTimes(self):
        return self._guessHis_.__len__()

    #输入字符串的格式转换
    def ChangeInputNumberFormat(self, numberStr):
        parseNum = NumberItem()
        if (numberStr.isdigit()):
            for eachNum in numberStr:
                parseNum._num_.append(int(eachNum))

        return parseNum

    #打印竞猜历史
    def ShowGuessHis(self):
        print ''
        print '你已经猜了 %d次, 总共%d次机会' % (self.GetGuessTimes(), self._MAX_GUESS_TIMES_)
        print ''

        for eachItem in self._guessHis_:
            eachItem.ShowItem()
        print ''

    def ShowHelp(self):
        print ''
        print '输入 'help' 显示命令列表.'
        print '输入 'his' 显示竞猜历史'
        print '输入 'cheat' 显示作弊结果'
        print '输入 'quit' 结束游戏'
        print ''

    def ShowCheat(self):
        print ''
        print '要猜的数字是 ', self._guessNum_.GetNumber()
        print ''

    def StartOneGame(self):

        self.ResetGameDate()

        print '开始猜数字游戏!'

        self._guessNum_.RestRandomNumber()

        print '随机号码 [*' + ',*'*(self._guessNum_._GUESS_NUMBER_COUNT_-1) + ']已经生成,你有%d次机会!' % self._MAX_GUESS_TIMES_

        #猜中标志
        guess_result = False
        quit_flag = False

        while (self.GetGuessTimes() < self._MAX_GUESS_TIMES_
               and guess_result != True and quit_flag != True):

            print '你还剩%d次机会,输入你猜的数字:' % (self._MAX_GUESS_TIMES_- self.GetGuessTimes())
            input_str = raw_input();

            if (input_str == 'help'):
                self.ShowHelp()
            elif(input_str == 'his'):
                self.ShowGuessHis()
            elif(input_str == 'cheat'):
                self.ShowCheat()
            elif(input_str == 'quit'):
                quit_flag = True
            else:
                #转换输入并校验
                hisItem = GuessHisItem()

                hisItem._guessNum_ = self.ChangeInputNumberFormat(input_str)
                if (hisItem._guessNum_.IsFormat() != True):
                    print '数字格式错误, 重新输入!'
                else:

                    #竞猜历史
                    hisItem._guessResult_ = self._guessNum_.CheckNumber(hisItem._guessNum_)
                    self._guessHis_.append(hisItem)

                    hisItem.ShowItem()

                    #猜中
                    if (hisItem._guessResult_._guess_A_ == NumberItem._GUESS_NUMBER_COUNT_):
                        guess_result = True
                        print '恭喜,你猜中了数字' , self._guessNum_.GetNumber() , ' 用了%d次机会' % self.GetGuessTimes()
                    elif(self.GetGuessTimes() == self._MAX_GUESS_TIMES_ ):
                        print ''
                        print '挑战失败,你已经猜了%d次,' % self.GetGuessTimes(), '正确的数字是', self._guessNum_.GetNumber()

        return quit_flag

    def StartGame(self):
        quit_flag = False
        while(quit_flag != True):

            quit_flag = self.StartOneGame()

            if (quit_flag != True):
                print ''
                print '再玩一局?(Y/N)'
                input_str = raw_input();

                if (input_str != 'Y'):
                    quit_flag = True

        print '再见!'

###### MAIN #######
if __name__ == '__main__':
    game = GuessNumberGame()
    game.StartGame()

 

以上的代码部分参考自:http://outofmemory.cn/


计算逆波兰算式
#!/usr/bin/env python
#coding=utf-8
class Solution:
    def add( self, num1, num2 ):
        return num1 + num2

    def sub( self, num1, num2 ):
        return num1 - num2

    def mul( self, num1, num2 ):
        return num1 * num2

    def div( self, num1, num2 ):
        if num1 * num2 < 0:
            return -((-num1) / num2 )
        return num1 / num2
    operator = { "+": add, "-": sub, "*": mul, "/": div }

    def evalRPN(self, tokens):
        nums = []
        for s in tokens:
          if s in ["+","-","*","/"]:
            num2 = nums.pop()
            num1 = nums.pop()
            re = self.operator.get(s)(self,num1,num2)
            nums.append(re)
          else:
            nums.append(int(s))
        return nums[0]

testS = Solution()
expression = ["2", "1", "+", "3", "*"]
print testS.evalRPN(expression)     #((2 + 1) * 3) -> 9
expression2 = ["4", "13", "5", "/", "+"]
print testS.evalRPN(expression2)    #(4 + (13 / 5)) -> 6

代码源于Evaluate Reverse Polish Notation

 

Python的字符串格式化

字符串格式化使用字符串格式化操作符,即%来实现。在%的左侧放置一个字符串(格式化字符串),而右侧则放置希望格式化的值。可以使用一个值,如一个字符串或者数字;也可以使用多个值的元组或者字典。一般情况下使用元组:

>>> format = 'Hello, %s. %s enough for ya?'
>>> values = ('world', 'Hot')
>>> print format % values
Hello, world. Hot enough for ya?

注:

(1)如果使用列表或者其他序列代替元组,那么序列就会被解释成一个值。只有元组和字典可以格式化一个以上的值。

(2)如果要在格式化字符串里面包括百分号,那么必须使用%%,这样Python就不会将百分号误认为是转换说明符了。

>>> format = 'The rate is %s%, so low'
>>> values = 31.0
>>> print format % values
Traceback (most recent call last):
  File "<stdin>", line 1, in <module> TypeError: not enough arguments for format string

 

>>> format = 'The rate is %s%%, so low'
>>> values = 31.0
>>> print format % values
The rate is 31.0%, so low

如果要格式化实数,可以使用f说明符类型,同时提供所需要的精度:一个句点再加上希望保留的小数位数。因为格式化说明符总是以表示类型的字符结束,所以精度应该放在类型字符的前面:

>>> format = 'Pi with three decimals: %.3f'
>>> from math import pi
>>> print format % pi
Pi with three decimals: 3.142

格式化操作符的右操作数可以是任何东西,如果是元组或者映射类型,那么字符串格式化将会有所不同。

如果右操作数是元组的话,则其中的每一个元素都会被单独格式化,每一值都需要一个对应的转换说明符。

注意:如果需要转换的元组作为转换表达式的一部分存在,那么必须将它用圆括号括起来,以避免错:

>>> '%s plus %s equals %s' % (1, 1, 2)
'1 plus 1 equals 2'

>>> '%s plus %s equals %s' % 1, 1, 2 # Lacks parentheses!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module> TypeError: not enough arguments for format string
格式 描述
%% 百分号标记
%c 字符及其ASCII码
%s 字符串
%d 有符号整数(十进制)
%u 无符号整数(十进制)
%o 无符号整数(八进制)
%x 无符号整数(十六进制)
%X 无符号整数(十六进制大写字符)
%e 浮点数字(科学计数法)
%E 浮点数字(科学计数法,用E代替e)
%f 浮点数字(用小数点符号)
%g 浮点数字(根据值的大小采用%e或%f)
%G 浮点数字(类似于%g)
%p 指针(用十六进制打印值的内存地址)
%n 存储输出字符的数量放进参数列表的下一个变量中

==字符串格式化代码==

参考链接:
,

《“一些Python片段_4 & Python字符串格式化”》 有 1 条评论

  1. 从两道CTF实例看python格式化字符串漏洞
    https://www.anquanke.com/post/id/170620
    `
    什么是python格式化字符串漏洞
     python常见的格式化字符串
    SWPUCTF 皇家线上赌场
     文件读取
     绕过目录限制
     format格式化字符串漏洞
    百越杯Easy flask
     环境搭建
     用户遍历
     源码审计
     format格式化字符串
    Session伪造
    总结
    参考文章
    `

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注