分类 "Python" 的存档.

python2分割有plist文件的精灵表(TexturePacker的线上版)

  置顶更新:最近写了一个MAC版的APP来分割有plist文件的精灵表(照顾用python脚本总是出现问题的朋友),请移步至https://github.com/afantree/CutPicture。点击下载按钮即可下载,也可自己下载code手工编译。

==========时间分割线==========

  曾经有一个朋友给我说我以前写的文章《python2_04分割有plist文件的精灵表》有问题,原因是图片资源打包器常见的有两种,Zwoptex 和 Texture Packer,他们生成的XML(plist)文件的格式是不一样的,我的这个是解析Zwoptex 生成的png 和 plist。
  今天又有一个朋友有过来问我,我把资源文件要过来分析了一下,发现这个文件还是用Texture Packer打包的,我的这个代码不适用的。为了适用Texture Packer的打包,我现在原来的基础上再写一个脚本吧。他是从线上的APP中直接拿来的素材,这个我在操作的过程中,还遇到了一些问题,现在也记一下。
阅读更多…

Python PyQuery库的使用总结

一、简介

pyquery库是jQuery的Python实现,可以用于解析HTML网页内容,我个人写过的一些抓取网页数据的脚本就是用它来解析html获取数据的。他的官方文档地址是:http://packages.python.org/pyquery/。今天重新看了一遍整个文档,把它的一些使用方法整理了一下,做个记录。
阅读更多…

python string 操作

去空格及特殊符号

s.strip().lstrip().rstrip(',')

复制字符串

#strcpy(sStr1,sStr2)
sStr1 = 'strcpy'
sStr2 = sStr1
sStr1 = 'strcpy2'
print sStr2

阅读更多…

Python list 操作

创建列表
sample_list = []

Python 列表操作
sample_list = [‘a’,’b’,0,1,3]

得到列表中的某一个值
value_start = sample_list[0]
end_value = sample_list[-1]
阅读更多…

python2_04分割有plist文件的精灵表

  置顶更新:最近写了一个MAC版的APP来分割有plist文件的精灵表(照顾用python脚本总是出现问题的朋友),请移步至https://github.com/afantree/CutPicture。点击下载按钮即可下载,也可自己下载code手工编译。

==========时间分割线==========

  昨天写了Zwoptex生成精灵表,有合就有分,能不能把合成的文件再原模原样的还原回来,哈哈……于是,今天利用闲暇的时间想一个问题:plist是用xml格式的,强大的python中的PIL(Python Imaging Library)可以处理各种图片,更不用说png图片了。
  昨天分析过plist,除了一个名字外,今天还能用上的还有两个属性,原始的文件的尺寸大小(这必须得要)和纹理在精灵表中的位置和大小,因为对xml的操作不太多,只是读取数据,就选用轻量级的ElementTree,把从xml解析出来的字符串数据转换成int类型,这就得到了图片属性的真实数据,这在精灵表上复制那个区域内的图片,然后在粘贴到新建的图片里面,哈哈,这样就搞定了。
  在操作的时候会用到PIL库,自己到官网下载源码安装。
  大概的思路是说出来啦, 阅读更多…

python3_03发送邮件

  今天看了一下怎么用python3发邮件?遇见的主要问题还是字符的编码问题
  问题1:遇见UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128)。还是utf-8的问题,解决办法:用Header()显示的转换成UTF-8编码,这下问题就解决了。

代码如下:

# ------- sendmail.py -------  
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "xxxx@qq.com"
you = "xxxx@qq.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('问候','utf-8')
msg['From'] = Header('猜猜我是谁','utf-8')
msg['To'] = you

text = "Hi!\n中文How are you?\nHere is the link you wanted:\n"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!呵呵<br>
       How are you?<br>
       解决个编码问题,可以发中文邮件了!
    </p>
  </body>
</html>
"""
part1 = MIMEText(text, 'plain','utf-8')
part2 = MIMEText(html, 'html','utf-8')

msg.attach(part1)
msg.attach(part2)
#print(msg.as_string())
s = smtplib.SMTP('smtp.xx.com','port')
s.login('name','password')
s.sendmail(me, you, msg.as_string())
s.quit()
print("OK")

参考:
#####class email.mime.application.MIMEApplication(_data, _subtype=’octet-stream’, _encoder=email.encoders.encode_base64, **_params)
Module: email.mime.application
A subclass of MIMENonMultipart, the MIMEApplication class is used to represent MIME message objects of major type application. _data is a string containing the raw byte data. Optional _subtype specifies the MIME subtype and defaults to octet-stream.
Optional _encoder is a callable (i.e. function) which will perform the actual encoding of the data for transport. This callable takes one argument, which is the MIMEApplication instance. It should use get_payload() and set_payload() to change the payload to encoded form. It should also add any Content-Transfer-Encoding or other headers to the message object as necessary. The default encoding is base64. See the email.encoders module for a list of the built-in encoders.
_params are passed straight through to the base class constructor.
#####class smtplib.SMTP
login(self, user, password)
Log in on an SMTP server that requires authentication.
The arguments are:
– user: The user name to authenticate with.
– password: The password for the authentication.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
This method will return normally if the authentication was successful.

python3_02spider抓取网页内容

  这个也研究了半天,主要是编码的问题,
  问题1:显示的全部是字符,中文显示的是乱码,查一下文档,原来urllib.request.urlopen打开的是一个对象,调用read()后,返回的是二进制的字符流,需要转换成汉字。
  问题2:在转换的时候,我用decode()方法,结果出现错误:UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xb0 in position 101: invalid start byte。因为decode()方法是把字符串转换成utf-8的编码,一般的情况中文的字符编码是GB2312,我就转换一下试试,用str()的方法转化,结果OK!
  代码解析:

# ------- spider.py -------  
import urllib.request
from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)
    def handle_endtag(self, tag):
        print("End tag  :", tag)
    def handle_data(self, data):
        print("Data     :", data)
    def handle_comment(self, data):
        print("Comment  :", data)
    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)
    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)
    def handle_decl(self, data):
        print("Decl     :", data)

f = urllib.request.urlopen("http://www.baidu.com")
if f.code == 200:
    parser = MyHTMLParser(strict=False);
    parser.feed(str(f.read(),'GB2312'))
    f.close()

参考:
handle_charref(self, name)
# Overridable — handle character reference
This method is called to process decimal and hexadecimal numeric character references of the form &#NNN; and &#xNNN;. For example, the decimal equivalent for > is >, whereas the hexadecimal is >; in this case the method will receive ’62’ or ‘x3E’.

handle_comment(self, data)
# Overridable — handle comment

handle_data(self, data)
# Overridable — handle data

handle_decl(self, decl)
# Overridable — handle declaration

handle_endtag(self, tag)
# Overridable — handle end tag

handle_entityref(self, name)
# Overridable — handle entity reference
This method is called to process a named character reference of the form &name; (e.g. >), where name is a general entity reference (e.g. ‘gt’).

handle_starttag(self, tag, attrs)
# Overridable — handle start tag

python_01提取文件夹里文件名

  Python像一个雕刻刀。
  见识一下python的强大,简短的几句,就能完成一个工作,虽然C,java都能实现,但是比较起来,还是python简单。比如提取文件名。

# --- picknames.py ---  
import os  
filenames=os.listdir(os.getcwd())  
for name in filenames:  
    filenames[filenames.index(name)]=name[:-3]  
out=open('names.txt','w')  
for name in filenames:  
    out.write(name+'\n')  
out.close()

解释一下:
1.导入os模块
2.
①getcwd(…)
getcwd() -> path
Return a unicode string representing the current working directory.
②listdir(…)
listdir([path]) -> list_of_strings
Return a list containing the names of the entries in the directory.
path: path of directory to list (default: ‘.’)
The list is in arbitrary order. It does not include the special
entries ‘.’ and ‘..’ even if they are present in the directory.
filenames接收了一个列表
3.4.截取一下字符串,就是把后面的后缀名给截去
③index(…)
index(value, [start, [stop]]) -> integer —
return first index of value.
5.打开一个文件
6.7.往文件中写下弄好的list
8.关闭文件
备注:①②③来自module docs