1.替换字符串中带有{$.key}的表达式
例1:text="Mrs {$.name} is a {$.job},she works at {$.compay}."
keys={"name":"Tom Anny","job":"teacher","compay":"ANi Middle School"}
输出:Mrs Tom Anny is a teacher,she works at ANi Middle School.
解析:用正则最简单,需掌握正则表达的语法
思路:①先正则匹配表达式,匹配成功,则替换,匹配失败则返回原字符串
②替换完成后继续递归,重复第一步
import re
def repalce_key_express(string,data):
pattern = re.compile(r"\{\$\.[a-zA-Z_0-9]+\}")
try:
s = pattern.search(string).group()
except AttributeError:
return string
else:
key = s[3:-1]
string = string.replace(s,data.get(key))
return repalce_key_express(string,data)
if __name__ == "__main__":
data = {"name":"Anna","country":"USA"}
string = "{$.name} is form {$.country}."
s = repalce_key_express(string,data)
print(s)
2.python变量命名方式转java变量命名方式,比如:http_request_pre_header 转换为 httpRequestPreHeader
解析:第一种用split分割_,第二种用正则替换
import re
# 下划线转驼峰
# split分割
def convert_underline_tf_split(string):
if "_" not in string:
return string
else:
key_arr = string.split("_")
sub_key = key_arr[1:]
result = [k.capitalize() for k in sub_key]
result.insert(0,key_arr[0])
return "".join(result)
# 正则替换
def convert_underline_tf_re(string):
pattern = re.compile("_[a-z0-9]")
try:
s = pattern.search(string).group()
except AttributeError:
# 无匹配则退出
return string
else:
string = string.replace(s,s[1].upper())
return convert_underline_tf_re(string)
if __name__ == "__main__":
string = "htt_reques_pre_header"
s1 = convert_underline_tf_split(string)
s2 = convert_underline_tf_re(string)
print(s1)
print(s2)
感兴趣的考虑下java变量命名方式转python变量命名方式
3.统计某目录下的图片文件的个数,不能用os.walk
解析:就是一个递归的计算问题,遍历目录和子目录,将各个目录下的匹配文件累加
思路:①遍历主目录,如果主目录下面文件名后缀匹配,则计数+1,如果是文件夹则递归访问子目录,将子目录的匹配文件个数累加
import os
def count_pic_nowalk(path):
pic = (".jpg",".png",".gif")
n = 0
try:
for sub in os.listdir(path):
sub_path = os.path.join(path,sub)
# 判断sub_path是否为目录
if os.path.isdir(sub_path):
# 如果是目录,累加子目录的匹配文件个数
n = n + count_pic_nowalk(sub_path)
else:
# 如果不是目录,则判断文件后缀
if x.endswith(pic):
n = n + 1
print(sub_path)
except:
# 权限问题不能访问
pass
return n
if __name__ == "__main__":
cnt = count_pic_nowalk(r"d:\\")
print(cnt)
如果用os.walk,os.walk会返回一个生成器generate,用for遍历目录下的所有目录,文件夹和文件,这样就不涉及递归了
import os
def count_pic_walk(path):
pic = (".log",".gif")
n = 0
for (base_dir,folders,files) in os.walk(path):
for f in files:
if f.endswith(pic):
n = n + 1
return n
if __name__ == "__main__":
cnt = count_pic_walk(r"D:\web")
print(cnt)
4.将明文中的数字翻译成密文,并列出所有的密文组合,"0":["0"],"1":["1"],"2":["A","S","D"],"3":["J","F","G"],"4":["T"],"5":["M","K"],"6":["P","C"],"7":["Y"],"8":["R","E"],"9":["N","Z"]
例1:23的可能密文为(AJ,AF,AG,SJ,...)
解析:这道题目比较简单,是一个字符串的列表推导式
思路:①如果字符长度为1,则返回密码映射
②如果字符长度超过1,比如字符串长度为2,前后2位字符的密码映射分别为l1和l2,用for依次遍历l1,l2,每一次遍历就是一次密码组合,代码表示如下
def listx(l1,l2):
result = []
for m in l1:
for n in l2:
result.append(m+n)
retrun result
用列表推导式就是[m+n for m in l1 for n in l2]
③如果是3个字符,就是第二步的结果再与第三个字符的再进行一次listx计算
④依次类推,长度为N>1的字符的密码组合就是进行N-1次计算,每一次的计算结果为result,并且作为下一次l1的初始值
number_mapping = {
"0":["0"],
"1":["1"],
"2":["A","S","D"],
"3":["J","F","G"],
"4":["T"],
"5":["M","K"],
"6":["P","C"],
"7":["Y"],
"8":["R","E"],
"9":["N","Z"]
}
def get_number_mapping(string):
mapping = number_mapping.get(string)
if not mapping:
return string
else:
return mapping
def main(string):
if len(string) == 1:
# 字符长度为1
return get_number_mapping(string)
else:
# 字符长度>1
n = 0
result = []
while(n<len(string)-1):
l1 = get_number_mapping(string[n]) if n == 0 else result
l2 = get_number_mapping(string[n+1])
result = [m + n for m in l1 for n in l2]
n = n + 1
return result
if __name__ == "__main__":
print(main("@#"))
print(main("3@"))
5.从字符串中提取关键字信息,并用<br></br>标记
例1:text="abcbbcc99afe",key=("abc","bbc")
输出:<br>abc</br><br>bbc</br>c99afe
例2:text="xabcaab99s5555",key=("abc","caa","s5")
输出:x<br>abcaa</br>b99<br>s5</br>555
例3:text="使用百度搜索python,请点击https://baidu.com",key=("百度","python","搜索","https://baidu.com")
输出:使用<br>百度搜索python</br>,请点击<br>https://baidu.com</br>
解析:例1,很容易找到关键字abc和bbc。但是例2,text="xabcaabffs5555",key=("abc","caa","s5"),匹配的第一个关键字是abc,找到开始节点和结束节点,abccaa是匹配了2个关键之abc和caa,这两个关键有重合,如果是重合关键字,则记为一个关键字,caa和下个关键字s5中间有其他字符串间隔,不为关键字。难点就在于关键字的识别。
思路:①划分关键字的边界是重点,首先找到第一个匹配的关键字位置的start和end
②遍历offset(取值范围1~len(string)-end-1),用string[start+1:end+1+offset]去匹配是否有endswith(keyword),然后判断是否重合(重合判断标准是:匹配关键的长度是否大于offset),如果不重合,则结束本次关键搜索,并将上一次的end作为关键字的结束index;如果重合记为重合关键字,并结束index为end = end + offset,重复第二步继续搜索关键字
③将第二步搜索到关键字string[start:end]保存
④从end+1继续重复1-3步骤找关键字
class NotMatchExcepiton(Exception):
pass
def get_first_key_index(string,key_arr,start=0):
while(len(string)>0):
for k in key_arr:
if string.startswith(k):
# 找到开始匹配关键字,返回开始和结束index
return start,start + len(k) -1
else:
# 从第二位开始继续寻找
sub_string = string[1:]
return get_first_key_index(sub_string,key_arr,start+1)
else:
# 遍历结束仍找不到开始index,则抛出异常
raise NotMatchExcepiton("Not match")
def get_key_end_index(string,key_arr,start,end):
offset = 1
while(offset<=len(string)-end-1):
tmp_string = string[start:end + 1 + offset]
for k in key_arr:
if tmp_string.endswith(k):
if len(k) >= offset:
# 重合,设置新结束index为end+offset
return get_key_end_index(string,key_arr,start,end + offset)
else:
# 不重合,记为结束index
return end
offset = offset + 1
else:
# 遍历结束后强制结束,并将最后一次得到的结束index返回
return end
def main(string,key_arr):
temp_list = []
while(len(string)>0):
try:
# 找到第一个匹配关键字的开始和结束index
start,end = get_first_key_index(string,key_arr)
if start>0:
temp_list.append(string[:start])
except NotMatchExcepiton:
# 如果找不到第一个匹配关键字,则当做普通字符串处理
temp_list.append(string)
break
else:
# 找第一个匹配关键字,如果多个有关键字有重合,则记为一个关键字,并找到结束index
end_x = get_key_end_index(string,key_arr,start,end)
temp_list.append("<br>"+string[start:end_x+1]+"</br>")
string = string[end_x+1:]
print(temp_list)
print("".join(temp_list))
if __name__ == "__main__":
s1="eABC99CDEFfowFFESEF99jsonwe677899fsok"
t1=("22","EF","555","Ffow","json","99","s","ABC","ok")
s2="xabcaab99s5555"
t2=("abc","caa","s5")
s3="畅销手机品牌有iphone,huawei,xiaomi,oppo,vivo等"
t3=("huawei","xiaomi")
s4="使用百度搜索python,请点击https://baidu.com"
t4=("百度","python","搜索","https://baidu.com")
main(s1,t1)
main(s2,t2)
main(s3,t3)
main(s4,t4)