• 字符串处理概述


    工作中有时会对各类文本进行处理。文本,即字符串。
    大部分使用正则表达式,部分直接使用python自带的方法

    1. 替换字符串中的url

    用于http,https和其他普通的url类型特殊字符

    import re
    def remove_urls (vTEXT):
        vTEXT = re.sub(r'(https|http)?://(w|.|/|?|=|&|\%)*', '', vTEXT, flags=re.MULTILINE)
        return(vTEXT)
    
    
    print( remove_urls("this is a test https://sdfs.sdfsdf.com/sdfsdf/sdfsdf/sd/sdfsdfs?bob=%20tree&jef=man lets see this too https://sdfsdf.fdf.com/sdf/f end"))
    

    2. 替换字符串中的英文字母(不含标点符号)

    import re
    str="我aksjnekljfklen,"
    temp = re.sub('[a-zA-Z]','',str)
    print(temp)
    

    3. 某个字符串在文本中出现的位置

    3.1 找到第一个出现的位置

    word = '木叶'
    str = '木叶飞舞之处,木叶的莲花'
    index = str.find(word)
    

    3.2 找到所有出现的位置

    def find_all_(source,dest):
    
        length1,length2 = len(source),len(dest)
        dest_list = []
        temp_list = []
        if length1 < length2:
            return -1
        i = 0
        while i <= length1-length2:
            if source[i] == dest[0]:
                dest_list.append(i)
            i += 1
        if dest_list == []:
            return -1
        for x in dest_list:
            #print("Now x is:%d. Slice string is :%s"% (x,repr(source[x:x+length2])),end=" ")
            if source[x:x+length2] != dest:
                #print(" dest != slice")
                temp_list.append(x)
            # else:
            #     print(" dest == slice")
    
        for x in temp_list:
            dest_list.remove(x)
        return dest_list
    

    4. 中文姓氏

    可以用来匹配文本中的'x师傅'……
    https://github.com/wainshine/Chinese-Names-Corpus

    book = xlrd.open_workbook("./tools/Chinese_Family_Name(1k).xlsx")
    sheet = book.sheet_by_index(0)
    for r in range(1,sheet.nrows):
        family_name = sheet.cell(r,0).value
        name_list.append(family_name)
    

    5. 中文人名

    使用hanlp中带词性的分词,人名对应的pos为'nr'。但是这种方法,很多人名其实被分为了姓+两个字。

    words = [_.toString() for _ in HanLP.segment(str)]
    for item in words:
        word,pos = item.split('/')
        if pos == 'nr':
            str = str.replace(word,'')
    
  • 相关阅读:
    bzoj 3456 城市规划 —— 分治FFT / 多项式求逆 / 指数型生成函数(多项式求ln)
    洛谷 P4721 [模板]分治FFT —— 分治FFT / 多项式求逆
    CF 438 E & bzoj 3625 小朋友和二叉树 —— 多项式开方
    Codeforces 447
    Codeforces 1099
    Codeforces 991
    Codeforces 994
    Codeforces 989
    Codeforces 1084
    xj膜你赛(n-1)
  • 原文地址:https://www.cnblogs.com/leimu/p/13631246.html
Copyright © 2020-2023  润新知