python处理中文字符的一点经验

本文介绍了一个Python脚本,用于对比两个文件夹中的文件,找出内容不同的文件,并记录结果。解决了路径中中文字符的编码问题,确保脚本在含有中文路径的环境下也能正常运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys, os
import md5

destPath = r'h:\路径A\测试'
srcPath = r'h:\路径B\测试'
rstPath = r'h:\路径C\rst.txt'

#----------------------------------------------------------------------
def find_all_files(path):
    '''
    '''
    print '\r\r'
    files = os.listdir(path.decode('utf8'))
    fileslist = []
    for ff in files:
        ffPath = path + '\\' + ff
        print ffPath,
        if os.path.isfile(ffPath):
            fileslist.append(ffPath)
            print 'file'
        elif os.path.isdir(ffPath):
            print 'dir'
            fileslist += find_all_files(ffPath)
        else:
            print 'parse error!', '\t', ffPath
    return fileslist

#----------------------------------------------------------------------
def md5_list(path):
    '''
    '''
    filesList = find_all_files(path)
    filesMd5 = {}
    for ff in filesList:
        try:
            fp = open(ff, 'rb')
            m = md5.md5()
            strRead = ""
            while True:
                strRead = fp.read(8096)
                if not strRead:
                    break
                m.update(strRead)
            strMd5 = m.hexdigest()
            filesMd5[strMd5] = ff
            fp.close()
        except Exception, ex:
            print ex
            fp.close()
    
    return filesMd5

if __name__=='__main__':
    reload(sys)
    sys.setdefaultencoding('utf-8')
    print 'Begin.......'   

    srcFilesMd5 = md5_list(srcPath)
    destFilesMd5 = md5_list(destPath)
    
    rst = ''
    for key in srcFilesMd5.keys():
        if key not in destFilesMd5.keys():
            fileName = srcFilesMd5[key]
            rst = rst + fileName.encode('utf8') + '\r'
    
    fp = open(rstPath, 'w')
    fp.write(rst)
    fp.close()
    
    print '\nRun Over......'

      此脚本能根据文件内容,从一个文件夹下找出不重复于另一个文件夹下的文件,并把结果记录在rstPath里。
      编写该脚本过程中遇到最大问题竟然是路径中的中文问题。以前也遇到过中文问题,但是都没有彻底搞清楚,只是试探的用decode()或encode()去解决。这次总算了解个大概,并总结出了一点经验。
       首先要明白的是,python里面默认的字符串都是ASCII编码,是string类型,ASCII编码处理中文字符是会出问题的。python的内部编码格式是unicode,在字符串前加‘u’前缀也可直接声明unicode字符串,如 u'hello'就是unicode类型。
如果处理的字符串中出现非ascii码表示的字符,要想不出错,就得转成unicode编码了。具体的方法有:
decode(),将其他边编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码;
encode(),将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码;
unicode(),同decode(),将其他编码的字符串转换成unicode编码,如unicode(str3, 'gb2312'),表示将gb2312编码的字符串str3转换成unicode编码。
转码的时候一定要先搞明白字符串str是什么编码,然后decode成unicode,最后再encode成其他编码。
      另外,对一个unicode编码的字符串在进行解码会出错,所以在编码未知的情况下要先判断其编码方式是否为unicode,可以用isinstance(str, unicode)。
      不仅是中文,以后处理含非ascii编码的字符串时,都可以遵循以下步骤:
1、确定源字符的编码格式,假设是utf8;
2、使用unicode()或decode()转换成unicode编码,如str1.decode('utf8'),或者unicode(str1, 'utf8');
3、把处理后字符串用encode()编码成指定格式。


<think>嗯,用户想了解Python字符串处理的函数。首先,我需要回忆Python中有哪些常用的字符串处理函数和方法。可能用户是刚开始学习Python,或者需要处理些字符串操作,比如分割、替换、查找等等。 首先,我应该分清楚哪些是内置函数,哪些是字符串对象的方法。比如len()是内置函数,而split()是字符串的方法。需要明确这一点,避免混淆用户。 接下来,常见的函数和方法有哪些呢?比如len(), str(), ord(), chr()这些内置函数。然后是字符串的方法,比如upper(), lower(), split(), join(), replace(), strip(), find(), startswith(), endswith()等等。可能还需要提到格式化方法,如format()和f-string。 用户可能需要些例子来说明每个函数的用法,这样更容易理解。比如split()的例子,用逗号分割字符串,或者用split()默认按空格分割。还有join()的用法,如何将列表连接成字符串。 另外,要注意些容易出错的地方,比如字符串是不可变的,所以方法返回的是新字符串,原字符串不变。比如replace()方法不会修改原字符串,而是返回新的字符串。 还要考虑用户可能的深层需求,比如他们可能在处理文件数据、用户输入或者网络爬虫时的字符串处理,所以需要覆盖到常用的场景,比如去除空白字符、大小写转换、查找子字符串等。 可能需要提醒用户注意编码问题,比如处理中文字符时确保文件编码正确,但这个问题可能稍微高级,暂时先不提,除非用户问到。 最后,组织这些内容,先介绍内置函数,再介绍字符串方法,每个部分给出简明扼要的解释和示例,保持结构清晰。确保用中文,避免使用专业术语过多,让初学者也能理解。</think>好的!Python 提供了丰富的字符串处理函数和方法,以下是些常用功能的分类整理,包含代码示例: --- ### **、基础操作** #### 1. 字符串长度 ```python s = "Hello" print(len(s)) # 输出 5 ``` #### 2. 类型转换 ```python num = 123 s = str(num) # 将其他类型转为字符串 print(s) # 输出 "123" ``` --- ### **二、大小写转换** ```python s = "Python" print(s.upper()) # 输出 "PYTHON" print(s.lower()) # 输出 "python" print("hello WORLD".capitalize()) # 输出 "Hello world" ``` --- ### **三、查找与替换** #### 1. 查找子串位置 ```python s = "apple banana" print(s.find("banana")) # 输出 6 (返回首次出现的索引) print(s.find("orange")) # 输出 -1 (未找到) ``` #### 2. 替换内容 ```python s = "I like Java" print(s.replace("Java", "Python")) # 输出 "I like Python" ``` --- ### **四、分割与拼接** #### 1. 分割字符串 ```python s = "a,b,c,d" print(s.split(",")) # 输出 ['a', 'b', 'c', 'd'] ``` #### 2. 拼接列表为字符串 ```python lst = ["2023", "10", "15"] print("-".join(lst)) # 输出 "2023-10-15" ``` --- ### **五、去除空白字符** ```python s = " Hello World " print(s.strip()) # 输出 "Hello World" (去首尾空格) print(s.lstrip()) # 去左空格 print(s.rstrip()) # 去右空格 ``` --- ### **六、格式化输出** #### 1. `format()` 方法 ```python name = "Alice" age = 25 print("{} is {} years old".format(name, age)) # 输出 "Alice is 25 years old" ``` #### 2. f-string (Python 3.6+) ```python print(f"{name} is {age} years old") # 效果同上 ``` --- ### **七、判断类方法** ```python s = "123abc" print(s.isdigit()) # 是否全为数字 → False print(s.isalpha()) # 是否全为字母 → False print(s.startswith("123")) # 是否以指定字符开头 → True ``` --- ### **八、字符编码转换** ```python print(ord("A")) # 输出 65 (字符→ASCII码) print(chr(65)) # 输出 "A" (ASCII码→字符) ``` --- ### **九、其他实用方法** ```python s = "python" print(s.center(10, "*")) # 输出 "**python**" (居中填充) print("hello".count("l")) # 统计出现次数 → 2 ``` --- ### **注意事项** 1. **字符串不可变**:所有操作会返回新字符串,原字符串不变。 2. **切片操作**:可通过 `s[start:end:step]` 灵活截取子串。 如果需要更具体的场景示例,可以告诉我你的需求! 😊
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值