美文网首页
Python3:bytes与str

Python3:bytes与str

作者: 我要当大佬 | 来源:发表于2017-10-17 10:16 被阅读0次

出处:https://wenku.baidu.com/view/c45ca1fd9ec3d5bbfd0a7491.html

在Python中,bytes和string是不同的东西。由一系列不可改变的Unicode字符组成的叫string。而一系列不可改变的介于0-255之间的数字被称为bytes对象。

来看示例:

>>> by = b'abcd\x65' #使用b''的格式定义bytes对象。每一个byte可以是一个ASCII字符或者十六进制数从\x00到\xff。

>>> by b'abcde'

>>> type(by)

>>> len(by)    #和list和string一样,可以使用内置的len()函数计算bytes对象的长度。

5

>>> by += b'\xff'  #和list和string一样,可以使用+操作符连接两个bytes对象。

>>> by b'abcde\xff'

>>> len(by)

6

>>> by[0]    #可以使用索引来访问bytes对象中的某一个byte 97>>> by[4] 101

>>> by[0] = 111   #bytes对象是不可改变的,不能对其赋值。

Traceback (most recent call last):

File "", line 1, in

TypeError: 'bytes' object does not support itemassignment

虽然我们不能对bytes对象直接赋值,但是我们可以将bytes转换为一个bytearray对象,bytearray对象是可以被修改的。

>>> barr = bytearray(by)

>>> barr

bytearray(b'abcde\xff')

>>> barr[0] = 120

>>> barr

bytearray(b'xbcde\xff')

bytes对象和string是不可以混在一起的。

>>> by

b’abcde\xff’

>>> s = “abcdefg”

>>> by + s

Traceback (most recent call last):

File ““, line 1, in

TypeError: can’t concat bytes to str

但是,bytes和string并不是毫无关系的,bytes对象有一个decode()方法,向该方法传递一个字符编码参数,该方法会返回使用该种编码解码后的字符串。同样的,string有一个encode()方法,完成反向的工作。

>>> string = "深入Python"

>>> len(string)

9

>>> by = string.encode('utf-8')   #将字符串编码为UTF8 >>> len(by) 13 >>> byb'\xe6\xb7\xb1\xe5\x85\xa5 Python'

>>> by = string.encode('gb18030')  #将字符串编码为GB18030 >>> len(by) 11

>>> by b'\xc9\xee\xc8\xeb Python'

>>> by.decode('gb18030')    #将bytes对象解码'深入Python'

例子:


# -*- coding: utf-8 -*-

"""

Created on Mon Oct 16 15:28:09 2017

@author: jssyhhghf

"""

import urllib

import re

import sys

import imp

class MovieTop250:

def __init__(self):

#设置默认编码格式为utf-8

imp.reload(sys)

#sys.setdefaultencoding('utf-8')

self.start = 0 #爬虫起始位置

self.param = '&filter=&type='

#User-Agent是用户代理,用于使服务器识别用户所使用的操作系统及版本、浏览器类型等,可以认为是爬虫程序的伪装。

self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64)'}

self.commentList = []

self.filePath = 'E:/anaconda/douban/douban.txt'

def getPage(self):

try:

URL = 'https://movie.douban.com/subject/25823277/comments?start=' +str(self.start)

request = urllib.request.Request(url = URL, headers = self.headers)

response = urllib.request.urlopen(request)

page =response.read().decode('utf-8')

pageNum = (self.start + 20)/20

print ('正在抓取第' +

str(pageNum) + '页数据...' )

self.start += 20

return page

except urllib.URLError as e:

if hasattr(e, 'reason'):

print ('抓取失败,具体原因:', e.reason)

def getMovie(self):

pattern = re.compile(u'.*?'

+u'.*?.*?'

+ u'(.*?)',re.S)

while self.start <= 100:

page = self.getPage()

comments = re.findall(pattern, page)

for comment in comments:

self.commentList.append([comment[0], comment[1].strip()]) #将捕获组数据写入评论List中

def writeTxt(self):

fileComment = open(self.filePath, 'wb')

try:

for comment in self.commentList:

fileComment.write(comment[1].encode('utf-8') + b'\r\n\r\n') #输出评论List数据

print ('文件写入成功...')

finally:

fileComment.close()

def main(self):

print ('正在从豆瓣电影三生三世抓取数据...')

self.getMovie()

self.writeTxt()

print ('抓取完毕...')

DouBanSpider = MovieTop250()

DouBanSpider.main()

相关文章

网友评论

      本文标题:Python3:bytes与str

      本文链接:https://www.haomeiwen.com/subject/jswruxtx.html