python小脚本合集

一些常用功能

打开json:

1
2
with open(jsonfile, 'r', encoding='utf8')as f:
json_data = json.load(f)

输出到json:

1
2
3
with open(jsonoutfile, 'a', encoding='utf8')as fp:
json.dump(templateData, fp)
fp.write('\n')#加了一个换行
1
2
3
4
cvedatas = []
cvedatas.append(templateData)
with open("cve.json", 'a', encoding='utf8')as f:
json.dump(cvedatas, f, ensure_ascii=False)

遍历目录:

1
2
3
files = os.listdir(cacheDirPath)
for file in files:
json_transfer(os.path.join(cacheDirPath, file), jsonFile)

翻译有道:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def get_translate_youdao(word):
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
Form_data = {
"i": word,
"from": "AUTO",
"to": "AUTO",
"smartresult": "dict",
"client": "fanyideskweb",
"salt": "1512399450582",
"sign": "78181ebbdcb38de9b4a3f4cd1d38816b",
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action": "FY_BY_CLICKBUTTION",
"typoResult": "false",
}
try:
response = requests.post(url, data=Form_data)
content = json.loads(response.text)
result = content["translateResult"][0][0]["tgt"]
return result
except:
return "wrong!"

根据正则匹配内容修改文件:

1
2
3
4
5
tem1 = 'script_template("FullScan"'
with open(xxfile, 'r', encoding='utf8')as f:
with open("final-"+xxfile, "w", encoding="utf-8")as f3:
for line in f:
f3.write(re.sub('script_template\(".*"', tem1, line))

不区分大小写匹配两个字符串:

1
2
3
4
5
for key in databasekey:
if(s1.lower().rfind(key.lower())) == -1 :
continue
else:
print(s1 + ":yes")