zoukankan      html  css  js  c++  java
  • python 中字符串处理

    在python 2或者3 ,字符串编码只有两类 :

    (1)通用的Unicode编码;
    (2)将Unicode转化为某种类型的编码,如UTF-8,GBK;

    计算机只处理数字,因此处理文本时,必须转换成数字才行。
    8位(bit)=1字节(byte)=256种不同状态=从000000到111111;
    1GB=1024M=1024(1024kb)=1024(1024(1024b));

    ASCII编码 是对应英文字符与二进制数字之间的关系;ASCII一共规定了128种,如大写字母A是65,即01000001;可见一字母一字节;

    GB2312编码 简体中文常见的编码,两个字节代表一个中文汉字 ,理论上256*256个编码,即可表示65536种中文字;

    各国编码不同,为了各国能扩平台进行文本的转换与处理,Unicode就被作为统一码或者单一码。Unicode编码通常是两个字节,unicode与ASCII编码的区别,在于unicode在ASCII编码前加了一个0,例如,字母A的ASCII编码为01000001,unicode编码即为00000000 01000001;但英文字母其实只用一个字节就够了,unicode编码写英文时多了一个字节,浪费存储空间。因而unicode开发了通用转换格式(Unicode Transformation Format(UTF)),常见的有utf-8或者utf-16;

    encode decode

    1)encode的作用是,将unicode对象编码成其他编码的字符串,str.encode('utf-8'),编码成UTF-8;(2)decode的作用是将其他编码的字符串转换成Unicode编码,str.decode('UTF-8');

    • import chardet 查阅具体的编码类型,chardet.detect(str),但是str不能是unicode编码类型,但是该方法 不接受 本来已经是unicode的编码的 参数,会有TypeError: Expected object of type bytes or bytearray, got: <type 'unicode'>错误;
    • 作为统一标准,unicode不能再被解码,如果UTF-8想转至其他非unicode,则必须(2)先decode 到unicode,在encode到其他非unicode的编码。

    解析出的汉字是:'xe4xb8xadxe5x9bxbd' 这种形式的(GBK编码),输出后就变成乱码了,所以应该先将其GBK解码,然后再UTF-8编码,然后再输出:

    decode('gbk').encode('utf-8')  

    输入一个汉字时通常要先对其UTF-8解码,然后再GBK编码:

    decode('utf-8').encode('gbk')  

    在json.dump or dumps 方法中输出中文:

    import json
    import sys
    
    reload(sys)
    sys.setdefaultencoding('utf-8')
    
    json_res = json.load(open('mrc - predictions.json', 'r', encoding='utf-8'))
    json.dump(json_res, open("json_res", "w"), ensure_ascii=False)

    dump()的第一个参数是要序列化的对象,第二个参数是打开的文件句柄,注意文件打开open()时加上以UTF-8编码打开,在dump()的时候也加上ensure_ascii=False,不然会变成ascii码写到json文件中json.dump(all_house,f,ensure_ascii=False,sort_keys=True, indent=4)

    json.dumps()/json.loads()等用法

    json_str = json.dumps(all_house,ensure_ascii=False); #all——books 为列表、字典等python自带的数据结构,将其写成json
    #print json_str; #[{"brokername": "小宝贝"},{},{}]
    new_dict = json.loads(json_str);#主要是读json文件时,需要用到
    #print new_dict; #{u'house_area': u'95', u'build_year': u'2005'}

    json.dumps() 是将一个Python数据结构转换为一个JSON编码的字符串,
    {"name": "shonababy"}

    json.loads() 是将一个JSON编码的字符串(字典形式)转换为一个Python数据结构,{u'name': u'shonababy'}

    dumps转化后键与值都变成了双引号,而在loads后变成python变量时,元素都变成了单引号,并且字符串前加多了个u
    一般要求当要字符串通过loads转为python数据类型时,得外层用单引号,里面元素key和value用双引号。

    • sort_keys:根据key排序

    dump与dumps的区别

    • dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)
    • dump将一个对象序列化存入文件,dump需要一个类似于文件指针的参数(并不是真的指针,可称之为类文件对象),可以与文件操作结合,也就是说可以将dict转成str存入文件中,如json.dump(all_house,f,ensure_ascii=False,sort_keys=True, indent=4)中的f表示一个数据待写入的json文件句柄
    • dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)
    • dumps(str)直接给的是str,也就是直接将字典转成str,无需写入文件,类似一个数据格式的转换方法,将python字符串转成json字典。
    • 所以dumps是将dict转化成str格式,loads是将str转化成dict格式。
    • dump和load也是类似的功能,只是与文件操作结合起来了。
    f=open('net_saving_data.txt','w',encoding='utf-8');
    for item in all_house:
        # house_area=item['house_area'];
        # price=item['price'];
        output='	'.join([str(item['house_area']),str(item['price']),str(item['build_year']),str(item['house_title'])]);
        f.write(output);
        f.write('
    ');
    f.close();

    中文写入txt、json文件是无非就是open()文件时,需要添加utf-8dump()时,需要添加ensure_ascii=False,防止ascii编码(此外注意python版本问题)

    读取网页数据的时候,查看网页的charset,及chardet库对编码类型的查询,及时进行decode和encode的编码转化,应该就能避免很多编码问题了。

    问题:

    UnicodeEncodeError: 'latin-1' codec can't encode character 'u5e74' in position 33: ordinal not in range(256)

    解决

    data = "u3010u6f14u5531u4f1au30112000-u62c9u9614u97f3u4e50u4f1a".encode("utf-8").decode("utf-8")
    print(type(data))
    print(data)
    
    C:Python36python.exe E:/work/1st_duty/demo3.py
    <class 'str'>
    【演唱会】2000-拉阔音乐会

    python2 解决TypeError: 'encoding' is an invalid keyword argument for this function

    环境:python2.7

    代码示例:

    with open('1.txt','r',encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            line =line.strip()

    使用with open() as f 语句提示错误:

    TypeError: 'encoding' is an invalid keyword argument for this function

    解决办法:

    import io
    with io.open('1.txt','r',encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            line =line.strip()
  • 相关阅读:
    《求医不如求己》1,2,3全集下载(附人体穴位图)
    Lambda 表达式(C# 编程指南)
    .NET生成静态页面的方案总结
    匿名函数(C# 编程指南)
    NameValueCollection详解
    sql数据库压缩的全面解析
    人的一生
    抓取博客园列表数据
    相对论的时空观
    C#中搜索关键词高亮显示
  • 原文地址:https://www.cnblogs.com/shona/p/12240185.html
Copyright © 2011-2022 走看看