问题提出:
有时候我们采集网页,处理完毕后将字符串保存到文件或者写入数据库,这时候需要制定字符串的编码,如果采集网页的编码是gb2312,而我们的数据库是utf-8的,这样不做任何处理直接插入数据库可能会乱码(没测试过,不知道数据库会不会自动转码),我们需要手动将gb2312转换成utf-8。
首先我们知道,python里的字符默认是ascii码,英文当然没问题啦,碰到中文的时候立马给跪。
不知道你还记不记得,python里打印中文汉字的时候需要在字符串前面加 u:
print u"来搞基吗?"
这样子中文才能显示,这里面的u的作用就是将后面的字符串转换为unicode码,这样中文才能得到正确的显示。
这里与之相关的有一个unicode()函数,用法如下
str="来搞基" str=unicode(str,"utf-8") print str
与u的区别是,这里用unicode将str转换为unicode编码,需要正确指定第二个参数,这里的utf-8是我test.py脚本自身的文件字符集,默认的可能是ansi。
unicode这是一个关键,下面继续
我们开始抓取百度首页,注意,游客访问百度首页,查看网页源代码,它的charset=gb2312。
import urllib2 def main(): f=urllib2.urlopen("http://www.baidu.com") str=f.read() str=unicode(str,"gb2312") fp=open("baidu.html","w") fp.write(str.encode("utf-8")) fp.close() if __name__ == '__main__' : main()
解释:
我们首先用urllib2.urlopen()方法将百度首页抓取到,f是句柄 ,用str=f.read()将所有源代码读入str中
搞清楚,str里面就是我们抓取的html源代码,由于网页默认的字符集是gb2312,所以如果我们直接保存到文件中,文件编码将是ansi。
对于大部分人来说,其实这就足够了,但是有时候我就想把gb2312转换成utf-8的该怎么办呢?
首先:
str=unicode(str,"gb2312") #这里的gb2312就是str的实际字符集,我们现在将其转换成unicode
然后:
str=str.encode("utf-8") #将unicode的字符串重新编码成utf-8
最后:
将str写入到文件中,打开文件看一下编码属性,发现是utf-8的了,把utf-8

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver Mac版
视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。