微信小程序 原生代码 转wepy 字符串处理

 

import glob
import os

cwd = os.getcwd()
sep = os.sep
target = cwd + sep + 'pages' + sep + '*' + sep + '*'
filelist = glob.glob(target)
pageNameSet = set([i.split('\\')[1] for i in glob.glob('./pages/*/*')])
pageStrDicList = {}
for i in pageNameSet:
pageStrDicList[i] = {'wxml': '', 'wxss': '', 'json': '', 'js': ''}

'''
Page页面字符串结构
<style lang="less">.wxss全部复制写入</style>
<template>.wxml全部复制写入</template>
<script>
import wepy from 'wepy'
.js Page({之前部分全部复制写入
export default class Index extends wepy.page {
config = {
.json全部复制写入
}
data = {.js data:的对象}
methods = { .js Page({ })中除去data:{}外的全部 }
}
</script>


'''

for i in filelist:
for pageName in pageNameSet:
try:
if pageName in i:
if i.endswith('wxml'):
with open(i, 'r', encoding='utf-8') as fr:
pageStrDicList[pageName]['wxml'] = fr.read()
elif i.endswith('wxss'):
with open(i, 'r', encoding='utf-8') as fr:
pageStrDicList[pageName]['wxss'] = fr.read()
elif i.endswith('json'):
with open(i, 'r', encoding='utf-8') as fr:
pageStrDicList[pageName]['json'] = fr.read()
elif i.endswith('js'):
with open(i, 'r', encoding='utf-8') as fr:
pageStrDicList[pageName]['js'] = fr.read()
break
except Exception as e:
print(i)
print(e)

for pageName in pageStrDicList:
try:
r = cwd + sep + 'res' + sep + pageName + '.wpy'
i = pageStrDicList[pageName]
s = '<style lang="less">\n' + i['wxss'] + '</style>\n'
s += '<template>\n' + i['wxml'] + '</template>\n'
s += '''
<script>
import wepy from 'wepy'
'''
l = i['js'].split('Page({')
s += l[0]
s += '''
export default class Index extends wepy.page {
config =
'''
s += i['json']
s += '\n'
if 'data:' in l[1]:
# js代码必须被微信ide格式化,这样保证data:存在且第一个满足要求
index_0 = l[1].index('data:')

index_1 = l[1][index_0:].index(' },')
s += '\ndata = ' + l[1][index_0:][5:index_1] + '}\n'

s += '\nmethods = {'
s += l[1][index_0 + 5 + (index_1 - 5) + len(' },'):].replace(': function', '').rstrip(' ').rstrip(
'\n').rstrip('})')
s += '}\n}'
else:
s += '\nmethods = {'
s += l[1][len('Page({') + 1:].replace(': function', '').rstrip(' ').rstrip(
'\n').rstrip('})')
s += '}\n}'
with open(r, 'w', encoding='utf-8') as fw:
fw.write(s)
except Exception as e:
print(e)
print(pageName)




 

posted @ 2018-09-01 20:52  papering  阅读(979)  评论(0编辑  收藏  举报