python 鱼c工作室作业_鱼C工作室Python作业
匿名用戶
1級
2017-07-04 回答
1,使用getopt。getopt()優化當前的功能函數:
[html]
#!/usr/bin/python
# -*- coding: utf-8 -*-
#coding=utf-8
import os,sys
import getopt
print sys.argv
CDROW='/home/zhouqian/test'
def cdWalker(CDROW,cdfile):
result=[]
for root,dirs,files in os.walk(CDROW):
result.append("%s %s %s" %(root,dirs,files))
print root
open(cdfile,'w').write('\n'.join(result))
def usage():
print '''pycdc 使用方式:
python cdays-3-exercise-1.py -d cdc -k 中國火
#檢索cdc中有沒有中國火字樣的目錄,
'''
try:
opts,args=getopt.getopt(sys.argv[1:],'hd:e:k:')
except getopt.GetoptError:
usage()
sys.exit()
if len(opts)==0:
usage()
sys.exit()
c_path=''
name=''
for opt,arg in opts:
if opt in('-h','--help'):
usage()
sys.exit()
elif opt=='-e':
if os.path.exists(arg):#判斷目標路徑是否存在
# cdWalker(CDROW,arg)
print "記錄光盤的位置是 %s" %arg
else:
print "不存在這樣的目錄"
elif opt=='-d':
c_path=arg
print c_path
cdWalker(CDROW,c_path)
elif opt=='-k':
if not c_path:
usage()
sys.exit()
else:
name=arg
for root,dirs,files in os.walk(c_path):
if root=='%s' %name:
print '您要找的文件在%s' %dirs
這是第一個題,大概做了2個小時吧,各種糾結啊,后面兩個正在做。中間遇到的問題總結:
函式的利用,os.path.walk,python字符集,getopt模塊的使用學習,os.path.exists()的利用,列表的對應關系等等
習題2 :關鍵詞-----》序列號問題:
[html]
#!/usr/bin/python
#coding=utf-8
import sys
def collect(file):
result={}
for line in file.readlines():
left,right=line.split()
if result.has_key(right):
result[right].append(left)
else:
result[right]=[left]
return result
if __name__=="__main__":
print sys.argv
if len(sys.argv)==1:
print 'usage:\tpython value_keys.py test.txt'
else:
result=collect(open(sys.argv[1],'r'))
for (right,left) in result.items():
print "%d %s => %s" %(len(left),right,left)
結果顯示:
[html]
root@zhou:/home/zhouqian/python# py value_keys.py test.txt
ssss
2 key3 => ['6', '33']
3 key2 => ['1', '2', '45']
3 key1 => ['4', '5', '13']
遇到的問題總結:
split的用法:line.split()就是分開出左右兩邊的值,在默認的情況下是以一個空格或者多個空格為分割符的,
has_key()的用法:是查看字典數據類型中有沒有這么一個關鍵字。上面可知result={}是初始化了一個字典的數據類型。
字典的一些用法:怎么定義,怎么賦值:result[right]=[left]或者result[right]=left,遍歷字典中所用
項,result.items(),遍歷字典的key值:result.keys(),遍歷字典的value值:result.values()
[html]
>>> dict={'chen':25,'zhou':24,'xiao':35}
>>> dict.values()
[25, 35, 24]
>>> dict.keys()
['chen', 'xiao', 'zhou']
>>> dict.items()
[('chen', 25), ('xiao', 35), ('zhou', 24)]
追問:
非常感謝您啊,能麻煩您給網頁截個圖嗎?
總結
以上是生活随笔為你收集整理的python 鱼c工作室作业_鱼C工作室Python作业的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python霍夫变换检测直线_OpenC
- 下一篇: python读取hdf文件 高效_利用p