Skip to content

python base64转码

Shuang0420 edited this page Jun 2, 2016 · 3 revisions

所谓Base64,就是说选出64个字符----小写字母a-z、大写字母A-Z、数字0-9、符号"+"、"/"(再加上作为垫字的"=",实际上是65个字符)----作为一个基本字符集。然后,其他所有符号都转换成这个字符集中的字符。 具体来说,转换方式可以分为四步。

  1. 将每三个字节作为一组,一共是24个二进制位。
  2. 将这24个二进制位分为四组,每个组有6个二进制位。
  3. 在每组前面加两个00,扩展成32个二进制位,即四个字节。
  4. 根据对照表表,得到扩展后的每个字节的对应符号,这就是Base64的编码值。

详细介绍可见

http://www.ruanyifeng.com/blog/2008/06/base64.html

本文仅介绍如何用python进行base64转码。

Python Base64

Python Base64 主要提供了以下几种方法: encode, decode,

encodestring, decodestring,

b64encode, b64decode,

standard_b64encode, standard_b64decode,

urlsafe_b64decode, urlsafe_b64encode。

这里只讲了最简单实用的encode,decode方法

首先需要导入模块

import base64

对字符串进行转码解码

可以把encodestring,decodestring替换为encode,decode

str1 = 'This is Test String'

#对字符串进行转码
enTest = base64.encodestring(str1)
print '转码后:',enTest

#对字符串进行解码
deTest = base64.decodestring(enTest)
print '解码后:',deTest

对文件进行转码解码

#读取文件进行编码
fr = open('/Users/Mr_Chen/Desktop/test.jpeg','rb')
fw = open('/Users/Mr_Chen/Desktop/testEncode.txt','wb')

#编码文件
base64Test = base64.encode(fr,fw)

#读取文件后进行解码
fr = open('/Users/Mr_Chen/Desktop/testEncode.txt','rb')
fw = open('/Users/Mr_Chen/Desktop/testDecode.jpeg','wb')

#解码文件
base64Test2 = base64.decode(fr,fw)

实例

下面一段代码的演示了如何将从百度百科爬下来的base64格式数据转码后进行分词存入文件,用于机器学习的训练。

import base64
import g_url_text_pb2
import jieba
def newFile():
    fw = open('tmp.txt','w')
    with open('baike_url_part_000.result') as f:
        for line in f:
	    # 对行进行解码
            base64Test = base64.b64decode(line)
            # 读取protobuf的message
            model=g_url_text_pb2.TextInfo()
            model.ParseFromString(base64Test)
            # 解码,忽略无法识别的编码
            doc = model.title.decode('gbk', 'ignore')+' '+(model.content.decode('gbk', 'ignore'))
            # 忽略换行符制表符等
            doc = "".join(doc.split())
            # 分词
            docwords = jieba.lcut(doc)
            # 写入文件
            fw.write(" ".join(docwords) + "\n")

参考链接

http://blog.csdn.net/a542551042/article/details/47018593

http://www.lai18.com/content/2756721.html

[[TOC]]

Clone this wiki locally