先來說我的需求:
用markdown寫文檔, 圖片是在本地的, 上傳到segmentfault或者github上時, 要把圖片轉換為網絡的鏈接, 有一個我用的方法就是上傳到 七牛上, 這樣不管是在哪里寫文檔, 直接復制上去就行了, 或者像github一樣需要轉換為網絡地址
這里提供兩個我寫的腳本
一個是上傳, 一個是把本地的圖片替換為網絡地址
上傳
```python
?```
# -*- coding: utf-8 -*-
# @Author: xsu19
# @Date: 2016-08-01 20:33:41
# @Last Modified by: xsu
# @Last Modified time: 2016-08-02 17:34:44
from qiniu import Auth, put_file, etag, urlsafe_base64_encode
import qiniu.config
import json
import os
import os.path
# 需要填寫你的 Access Key 和 Secret Key
access_key = '*'
secret_key = '*'
# 要上傳的空間
bucket_name = '*'
# 公開的http路徑
qiniu_path = '*'
# 上傳到七牛后保存的文件路徑
remote_path = 'pic/phpstorm/'
# 本地要上傳的圖片路徑
local_path = 'image/'
# 上面的請根據實際情況修改
# 構建鑒權對象
q = Auth(access_key, secret_key)
error_file = []
files_url = []
print("uploading...")
for filenames in os.walk(local_path):
for filename in filenames[2]:
key = remote_path + filename
token = q.upload_token(bucket_name, key, 3600)
# print(filename)
localfile = local_path + filename
# 上傳
ret, info = put_file(token, key, localfile)
is_hash_same = (ret['key'] == key) and (ret['hash'] == etag(localfile))
if not is_hash_same :
print(filename, "upload failed")
# 把上傳失敗的記錄到error_file中
error_file.append(localfile)
else:
files_url.append(qiniu_path + remote_path + filename)
# error_file not null
if error_file != []:
print(error_file, 'upload failed')
else:
print("uploaded")
?```
```
替換
```python
# -*- coding: utf-8 -*-
# @Author: xsu19
# @Date: 2016-08-01 20:33:41
# @Last Modified by: xsu
# @Last Modified time: 2016-11-01 10:16:04
import sys,os
import re
# todo 替換你的地址: 七牛的地址或者github的原始文件地址
addr = ''
if len(sys.argv) == 1:
print("arg is too little")
exit()
if len(sys.argv) > 3:
print("arg is too much")
exit()
if len(sys.argv) == 2:
input_file = sys.argv[1]
output_file = 'md/'+input_file
if len(sys.argv) == 3:
input_file = sys.argv[1]
output_file = sys.argv[2]
if input_file.find('.md') == -1 :
print("choose markdown file pls")
exit()
if not os.path.exists(input_file):
print("input markdown file not exists")
exit()
# 將正則表達式編譯成Pattern對象
pattern = re.compile(r'image\\')
replace = addr
# subject = "image\\20160730003958.jpg, image\\20160730003958.jpg"
# result, number = pattern.subn(replace, subject)
print("output file is "+output_file)
if input_file == output_file:
print("input file do not same with output file")
exit()
# 文件操作
i_file = open(input_file, 'r', encoding= 'utf8')
o_file = open(output_file, "w")
while True:
line = i_file.readline()
if not line:
break
# regx
result, number = pattern.subn(replace, line)
if number: # 如果匹配到了
o_file.write(result)
else: # 如果沒有匹配到
o_file.write(line)
#文件處理完,關閉
i_file.close()
o_file.close()
```