這篇文章主要講解了“Python怎么計(jì)算球的個(gè)數(shù)”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Python怎么計(jì)算球的個(gè)數(shù)”吧!
成都創(chuàng)新互聯(lián)網(wǎng)站建設(shè)由有經(jīng)驗(yàn)的網(wǎng)站設(shè)計(jì)師、開發(fā)人員和項(xiàng)目經(jīng)理組成的專業(yè)建站團(tuán)隊(duì),負(fù)責(zé)網(wǎng)站視覺設(shè)計(jì)、用戶體驗(yàn)優(yōu)化、交互設(shè)計(jì)和前端開發(fā)等方面的工作,以確保網(wǎng)站外觀精美、做網(wǎng)站、網(wǎng)站設(shè)計(jì)易于使用并且具有良好的響應(yīng)性。
代碼如下:
# author: DE8UG
# 創(chuàng)建垃圾桶和垃圾
# 規(guī)則:k:v,一個(gè)k對應(yīng)一個(gè)v,代碼表示用冒號分割
# 輸入
# 判斷
# 保存
# 函數(shù)
# 綜合
import json
rule = {
"濕垃圾": ["菜葉", "橙皮", "蔥", "餅干"],
"干垃圾": ["舊浴缸", "盆子", "海綿", "衛(wèi)生紙"]
}
# print('加載文件:', ljt_gan)
def load_data(filename):
with open(filename) as f:
data = json.load(f)
return data
def reng_laji(rule_k, laji, ljt):
if rule_k == ljt['name']:
ljt['data'].append(laji)
def fenlei(laji, rule, ljt):
for k, v in rule.items():
print(k, v)
if laji in v:
print('找到了垃圾:', laji, k)
reng_laji(k, laji, ljt)
# reng_laji(k, laji, ljt_shi)
# 用函數(shù)封裝寫文件的代碼
def save_to_file(filename, data):
with open(filename, 'w') as f:
json.dump(data, f)
def main():
# 定義垃圾桶
ljt_shi = {
'name': "濕垃圾",
'data': []
}
ljt_gan = {
'name': "干垃圾",
'data': []
}
# 加載已有的垃圾
ljt_gan = load_data('gan.json')
ljt_shi = load_data('shi.json')
print('加載文件:', ljt_gan, ljt_shi)
# 扔垃圾
laji = input("輸入要扔的垃圾:")
print("垃圾:", laji)
# 分類
fenlei(laji, rule, ljt_gan)
fenlei(laji, rule, ljt_shi)
print('-'*20)
print(ljt_shi)
print(ljt_gan)
# 調(diào)用函數(shù),保存到具體的垃圾桶文件
save_to_file('gan.json', ljt_gan)
save_to_file('shi.json', ljt_shi)
if __name__ == "__main__":
main()
這段代碼不長,但是包含了變量,注釋,函數(shù)等部分,可以用來做第一個(gè)分析目標(biāo)了。
以下內(nèi)容用代碼和注釋來解釋做了什么。
# Python算個(gè)球
# author:DE8UG
# 首先準(zhǔn)備好目標(biāo)文件
filename = 'rengleme_07.py'
# 寫函數(shù)得到里面所有行
def get_lines(filename):
with open(filename) as f:
return f.readlines()
# 執(zhí)行這個(gè)函數(shù)打印的話,會是下面這一大堆字符串,但,注意看,是個(gè)列表。那就好辦了
"""
['# author: DE8UG\n', '# 創(chuàng)建垃圾桶和垃圾\n',
'# 規(guī)則:k:v,一個(gè)k對應(yīng)一個(gè)v,代碼表示用冒號分割\n',
'# 輸入\n', '# 判斷\n', '# 保存\n', '# 函數(shù)\n', '# 綜合\n', '\n', '\n',
'import json\n', '\n', '\n',
'rule = {\n', ' "濕垃圾": ["菜葉", "橙皮", "蔥", "餅干"],
\n', '
"干垃圾": ["舊浴缸", "盆子", "海綿", "衛(wèi)生紙"]\n', '}\n',
'\n', '\n',
"# print('加載文件:', ljt_gan)\n",
'def load_data(filename):\n',
' with open(filename) as f:\n',
' data = json.load(f)\n',
' return data\n', '\n', '\n', 'def reng_laji(rule_k, laji, ljt):\n', " if rule_k == ljt['name']:\n", " ljt['data'].append(laji)\n", '\n', '\n', 'def fenlei(laji, rule, ljt):\n', ' for k, v in rule.items():\n', ' print(k, v)\n', ' if laji in v:\n', " print('找到了垃圾:', laji, k)\n", ' reng_laji(k, laji, ljt)\n', ' # reng_laji(k, laji, ljt_shi)\n', ' \n', '\n', '# 用函數(shù)封裝寫文件的代碼\n', 'def save_to_file(filename, data):\n', " with open(filename, 'w') as f:\n", ' json.dump(data, f)\n', '\n', '\n', 'def main():\n', '\n', ' # 定義垃圾桶\n', ' ljt_shi = {\n', ' \'name\': "濕垃圾",\n', " 'data': []\n", ' }\n', '\n', ' ljt_gan = {\n', ' \'name\': "干垃圾",\n', " 'data': []\n", ' }\n', '\n', ' # 加載已有的垃圾\n', " ljt_gan = load_data('gan.json')\n", " ljt_shi = load_data('shi.json')\n", '\n', " print('加載文件:', ljt_gan, ljt_shi)\n", '\n', ' # 扔垃圾\n', ' laji = input("輸入要扔的垃圾:")\n', ' print("垃圾:", laji)\n', '\n', ' # 分類\n', ' fenlei(laji, rule, ljt_gan)\n', ' fenlei(laji, rule, ljt_shi)\n', '\n', " print('-'*20)\n", ' print(ljt_shi)\n', ' print(ljt_gan)\n', '\n', ' # 調(diào)用函數(shù),保存到具體的垃圾桶文件\n', " save_to_file('gan.json', ljt_gan)\n", " save_to_file('shi.json', ljt_shi)\n", '\n', '\n', 'if __name__ == "__main__":\n', ' main()\n', '\n', '\n', '\n']
"""
# 我們定義一下結(jié)果格式,把每一行代碼格式化一下為字典,包含行號,字符串,類型,含義四部分,然后組合為新的列表
[
{
'line':1,
'str':'def load_data(filename):\n',
'type':'function', # code, comment, import, var
'mean':'函數(shù)load_data,包含參數(shù):filename'
}
]
def analysis_code(lines):
"""分析每一行代碼,根據(jù)不同特點(diǎn),劃分不同類型,注意換行的變量和函數(shù)會有內(nèi)部代碼,我們通過上一次保存的結(jié)果進(jìn)行分解判斷。把格式化后的行保存為新列表,并返回。
"""
results = []
count = 1
for line in lines:
format_line = {
'line': count,
'str': line,
'type':'code', # code, comment, import, var
'inner_code': [],
'mean':''
}
if line.startswith('#'):
format_line['type'] = 'comment'
elif line.startswith('import'):
format_line['type'] = 'import'
elif line.find('=') > 0:
format_line['type'] = 'var'
elif line.startswith('def'):
format_line['type'] = 'function'
# 空行,函數(shù)內(nèi)部代碼,變量內(nèi)部代碼,不加入結(jié)果
if line.startswith(' ') or line.startswith('}\n'):
# print(results[-1])
if results[-1]['type'] == 'function' or results[-1]['type'] == 'var':
results[-1]['inner_code'].append(line)
elif line.startswith('\n'):
pass # 空行直接掠過
else:
results.append(format_line)
# 循環(huán)下一行
count += 1
return results
# 下面開始測試
if __name__ == "__main__":
print('*'*50)
print('歡迎使用Python算個(gè)球,掐指一算,你的代碼內(nèi)容如下:')
lines = get_lines(filename)
# print(lines[:10])
r = analysis_code(lines)
# print(r)
comment_list = []
function_list = []
for line in r:
# print(line)
if line['type']=='comment':
comment_list.append(line)
elif line['type']=='function':
function_list.append(line)
print(f'- 共{len(comment_list)}個(gè)注釋')
print(f'- 共{len(function_list)}個(gè)函數(shù):')
for f in function_list:
print(f'line:{f["line"]}', f['str'].strip())
如代碼所示,我們今天把目標(biāo)代碼進(jìn)行了分解,根據(jù)每一行不同特點(diǎn)從新進(jìn)行了格式化,轉(zhuǎn)換為包含行號,字符串,類型,含義四部分的字典。這里還可以根據(jù)需要擴(kuò)展不同的格式,方便我們進(jìn)一步處理。比如解析代碼含義,描述運(yùn)行流程等。
感謝各位的閱讀,以上就是“Python怎么計(jì)算球的個(gè)數(shù)”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Python怎么計(jì)算球的個(gè)數(shù)這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!