python查找中文字符

#filename Seek.py
import unicodedata

import sys
import os
class Seek():
    """
    功能:查找中文,并替换成指定字符或字符串
    使用方法:python脚本用法
    参数说明:
        -d    : 文件目录(绝对或相对路径)(默认为脚本所在目录)
        -t    : 文件类型(文件名后缀,如.jsp;.txt)(默认为所有文件)
        -sf   : 是否包括子目录(Y|N)(option,默认不包括子目录)
        -r    : 输出文件名(option,默认为'ChineseCharacter.txt'),位于脚本目录下
        -encoding:文件字符编码(默认为utf-8)

    """
       
    def __init__(self):
        """
        初始化查找程序
        参数解析

        """
        #TODO:
        self.d = '.'
        self.sf = 'N'
        self.t = 'ALL'
        self.r = 'ChineseCharacter.txt'
        self.encoding = 'utf-8'
        varL = 0
        for ar in sys.argv:
            if ar == '-d':
                self.d = sys.argv[varL+1]
                continue

            if ar =='-sf':
                sf = sys.argv[varL+1].upper()
                if (sf == 'Y') | (sf == 'N'):
                    self.sf = sf
                else:
                    print('input error with sf parameter')
                continue

            if ar=='-r':
                self.r = sys.argv[varL+1]
                continue

            if ar=='-t':
                self.t = sys.argv[varL+1]
                continue
               
            if ar == '-encoding':
                self.encoding = sys.argv[varL+1]
                continue

            varL+=1

    def seeking(self):
        """"
        开始查找字符
       
        """
        try:
            #output file
            self.rfile = open(self.r,'w',encoding=self.encoding)
            #start seek
            for f in os.listdir(self.d):
                path = os.path.join(self.d,f)
                if self.__isFile(path):
                    if self.t != 'ALL':
                        if f.endswith(self.t):
                            self.__seek(path)
                    else:
                        self.__seek(path)
                elif self.__isDir(path) and self.sf == 'Y' :
                    #seek the sub folder when the self.sf equals 'Y'
                    self.start(path)
        except Exception as error:
            print('seek error %s' % error)
        finally:
            self.__close()
      
               
    def __close(self):
        """
        关闭文件及输入流和输出流

        """
        #close the stream and file
        self.rfile.close()

    def __isFile(self,file):
        #
        return os.path.isfile(file)
   
    def __isDir(self,path):
        #
        return os.path.isdir(path)
   
    def __openFile(self,file):
        pass
   
    def __closeFile(self,file):
        file.close()

    def __seek(self,file):
        """
        查找
       
        """
        #seek character
        fileObj = open(file,'r',encoding=self.encoding)
        lineList = fileObj.readlines()
        #块注释标记
        blockComment = 'finish'
        try:
            isC = False
            for line in lineList:
                #查找出注释部分,并跳过
                #
                #跳过'/*'和'*/'中的内容,处理剩余的内容
                if blockComment == 'start':
                    #块注释内容
                    index = line.find('*/')
                    if index != -1:
                        blockComment = 'finish'
                        #块注释结束
                        #处理当前行'*/'后的内容
                        line = line[index+2:]
                    else:
                        #仍处于块注释内容中,跳过
                        continue
                if line.startswith('//'):
                    #行注释
                    #跳过行
                    continue
                if line.startswith('/*'):
                    #块注释开始
                    blockComment = 'start'
                    continue

                #查找字符
                indexTag = 0;
                for s in line:
                    sIndex = line.index(s)
                    try:
                        #将不是LATIN开头的字符都找出来
                        if unicodedata.name(s).startswith('CJK') == True:
                            #TODO
                            #content = lineList.index(line)+1+s
                            isC = True
                            #如果两个字符间隔大于1,表示为不连续的中文
                            if (sIndex - indexTag) > 1 :
                                self.__writeFile('/t'+s)
                            else:
                                self.__writeFile(s)
                            indexTag = sIndex
                    except Exception as error:
                        print('seek character error : %s in %s' % (error,fileObj.name))
                        continue
                if isC:
                    for t in range(8):
                        self.__writeFile('/t')
                    self.__writeFile('line:')
                    self.__writeFile('%d' % (lineList.index(line)+1))
                    self.__writeFile('/n')
                isC = False
               
        finally:
            self.__writeFile('/n')
            self.__writeFile('------------'+fileObj.name)
            self.__writeFile('/n')
            fileObj.close()
       
    def __writeFile(self,content):
        self.rfile.write(content)
       
       
if __name__ == '__main__':
    seek=Seek()
    seek.seeking()

### 如何在 Python查找固定字符串Python 中,可以通过多种方式实现对固定字符串查找功能。以下是几种常见的方法及其具体应用: #### 使用 `in` 关键字 `in` 是一种简单而直观的关键字,用于判断一个子字符串是否存在于另一个字符串中。如果存在,则返回 `True`;否则返回 `False`。 ```python text = "这是一个示例字符串" substring = "示例" if substring in text: print(f"'{substring}' 存在于 '{text}' 中") # 输出结果表明 '示例' 是否存在 else: print(f"'{substring}' 不存在于 '{text}' 中") ``` 这种方法适用于简单的布尔判定场景[^1]。 #### 使用 `str.find()` 方法 `find()` 方法可以用来定位子字符串首次出现的位置。如果没有找到匹配项,则返回 `-1`。 ```python position = text.find(substring) if position != -1: print(f"'{substring}' 首次出现在位置 {position}") # 返回第一个匹配项的起始索引 else: print(f"'{substring}' 未被发现") ``` 此方法不仅能够检测是否存在目标子字符串,还能提供其确切位置信息[^2]。 #### 利用正则表达式模块 (`re`) 对于更复杂的模式匹配需求,可采用正则表达式的强大能力。通过导入标准库中的 `re` 模块完成高级搜索任务。 ```python import re pattern = r"示例" match = re.search(pattern, text) if match: start_pos = match.start() end_pos = match.end() print(f"使用正则表达式查找到'{substring}', 起始于位置 {start_pos}, 结束于位置 {end_pos}") else: print("未能通过正则表达式找到指定内容") ``` 当面对多条件约束或者动态变化的需求时,推荐优先考虑这种方式[^3]。 --- ### 总结 每种技术都有各自适用范围,在实际开发过程中应依据具体情况灵活选用最合适的工具来解决问题。无论是基本语法还是第三方扩展包的应用都需要不断积累经验才能熟练掌握并高效运用它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值