Ⅰ 求簡潔優美的python代碼例子、片段、參考資料
樓主貼的那段代碼好像是我寫的那段吧,我來告訴你如何寫出來的吧
首先我不是高手,我也沒有人教,我的編程都是自學的,我只是一個業余愛好者.
寫出這樣的代碼很簡單,就是要多練,我只是把python的基本語法學會,然後就不停地練習,我沒有看過樓上的那些資料,我只是不停地碼代碼,或許有捷徑,但是我沒有發現.
我從07年開始寫python的腳本,我一開始的代碼風格也很差,特別是我先學c++,然後再轉python的,當寫的代碼越來越多,對python的了解就會加深,代碼風格也會自動改變的,不需要著急,其實這就是對一門語言的了解程度,你可以看看我回答的問題,我的回答就是我對python的理解,如果你能堅持下來,相信7年後你寫的代碼會比我寫得更好.
樓上的題目有點意思,我也寫一下,不知道對否
s='''
TheZenofPython,byTimPeters
Beautifulisbetterthanugly.
Explicitisbetterthanimplicit.
Simpleisbetterthancomplex.
.
Flatisbetterthannested.
Sparseisbetterthandense.
Readabilitycounts.
Specialcasesaren'tspecialenoughtobreaktherules.
.
Errorsshouldneverpasssilently.
Unlessexplicitlysilenced.
Inthefaceofambiguity,refusethetemptationtoguess.
Thereshouldbeone--andpreferablyonlyone--obviouswaytodoit.
'reDutch.
Nowisbetterthannever.
*right*now.
,it'sabadidea.
,itmaybeagoodidea.
--let'sdomoreofthose!
'''
importre,collections
tail_map={"'s":'is',"'re":'are',"n't":'not'}
data=collections.Counter(re.findall('w+',re.sub("('s|'re|n't)",lambdamatchobj:tail_map[matchobj.group()],s.lower())))
max_len=max(data.values())
print('Totalwordcount:%d',sum(data.values()))
forwordinsorted(data):
print('%*s=>%d'%(max_len,word,data[word]))
Ⅱ 如何使用python編寫測試腳本
1)doctest
使用doctest是一種類似於命令行嘗試的方式,用法很簡單,如下
復制代碼代碼如下:
def f(n):
"""
>>> f(1)
1
>>> f(2)
2
"""
print(n)
if __name__ == '__main__':
import doctest
doctest.testmod()
應該來說是足夠簡單了,另外還有一種方式doctest.testfile(filename),就是把命令行的方式放在文件里進行測試。
2)unittest
unittest歷史悠久,最早可以追溯到上世紀七八十年代了,C++,Java里也都有類似的實現,Python里的實現很簡單。
unittest在python里主要的實現方式是TestCase,TestSuite。用法還是例子起步。
復制代碼代碼如下:
from widget import Widget
import unittest
# 執行測試的類
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget()
def tearDown(self):
self.widget.dispose()
self.widget = None
def testSize(self):
self.assertEqual(self.widget.getSize(), (40, 40))
def testResize(self):
self.widget.resize(100, 100)
self.assertEqual(self.widget.getSize(), (100, 100))
# 測試
if __name__ == "__main__":
# 構造測試集
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase("testSize"))
suite.addTest(WidgetTestCase("testResize"))
# 執行測試
runner = unittest.TextTestRunner()
runner.run(suite)
簡單的說,1>構造TestCase(測試用例),其中的setup和teardown負責預處理和善後工作。2>構造測試集,添加用例3>執行測試需要說明的是測試方法,在Python中有N多測試函數,主要的有:
TestCase.assert_(expr[, msg])
TestCase.failUnless(expr[, msg])
TestCase.assertTrue(expr[, msg])
TestCase.assertEqual(first, second[, msg])
TestCase.failUnlessEqual(first, second[, msg])
TestCase.assertNotEqual(first, second[, msg])
TestCase.failIfEqual(first, second[, msg])
TestCase.assertAlmostEqual(first, second[, places[, msg]])
TestCase.failUnlessAlmostEqual(first, second[, places[, msg]])
TestCase.assertNotAlmostEqual(first, second[, places[, msg]])
TestCase.failIfAlmostEqual(first, second[, places[, msg]])
TestCase.assertRaises(exception, callable, ...)
TestCase.failUnlessRaises(exception, callable, ...)
TestCase.failIf(expr[, msg])
TestCase.assertFalse(expr[, msg])
TestCase.fail([msg])
Ⅲ 用PYTHON寫腳本
importos
#在當前目錄下創建文件夾
os.mkdir('newfile')
os.mkdir('newfile/commence')
#或者直接用下面這條代碼一次性創建這兩個文件夾
#os.makedirs('newfile/commence')
Ⅳ Python如何調用別人寫好的腳本
import腳本文件名,和導入模塊是一樣的。
如果只是代碼片段,直接復制到自己的代碼中也可以。
Ⅳ python腳本第一行怎麼寫
python腳本第一行的寫法:【#!/usr/bin/env python】。該語句告訴操作系統執行該腳本時,首先到env設置里查找python的安裝路徑,然後調用對應路徑下的解釋器程序完成操作。
腳本語言的第一行的目的就是指出,你想要你的這個文件中的代碼用什麼可執行程序去運行它。
(推薦教程:Python入門教程)
寫法:
#!/usr/bin/python是告訴操作系統執行這個腳本的時候,調用/usr/bin下的python解釋器。
#!/usr/bin/env python這種用法是為了防止操作系統用戶沒有將python裝在默認的/usr/bin路徑里。當系統看到這一行的時候,首先會到env設置里查找python的安裝路徑,再調用對應路徑下的解釋器程序完成操作。
#!/usr/bin/python相當於寫死了python路徑。
#!/usr/bin/env python會去環境設置尋找python目錄(建議寫法)。
Ⅵ 如何讓python腳本在關閉的時候運行一段代碼
如果是命令行的,一般是捕獲ctrl-c事件吧。
import signal
import sys
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
如果是基於GUI框架開發的,都有事件觸發的,你重載事件就好了。比如Qt就有closeEvent事件
Ⅶ 這段代碼是什麼意思這是python的一個腳本嗎,這裡面的call是什麼意思,求大神
看樣子是一個比較大的項目里的一個腳本。首先要明確這是一個windows的批處理腳本,並不是python腳本。
再大概看了下其內容,似乎是一個有關數據處理的軟體(BI即商業智能),這種類似軟體有可能會依賴於一些現有的數據處理庫(多半是python寫的),這個腳本的作用就是調用一些列工具把python代碼轉換成windows下的exe。
Ⅷ 關於Python中的一段為Python腳本添加行號腳本
C語言有__LINE__來表示源代碼的當前行號,經常在記錄日誌時使用。Python如何獲取源代碼的當前行號?
The C Language has the __LINE__ macro, which is wildly used in logging, presenting the current line of the source file. And how to get the current line of a Python source file?
exception輸出的函數調用棧就是個典型的應用:
A typical example is the output of function call stack when an exception:
python代碼
File "D:\workspace\Python\src\lang\lineno.py", line 19, in <mole>
afunc()
File "D:\workspace\Python\src\lang\lineno.py", line 15, in afunc
errmsg = 1/0
ZeroDivisionError: integer division or molo by zero
那麼我們就從錯誤棧的輸出入手,traceback模塊中:
Now that, Let's begin with the output of an exception call stack, in the traceback mole:
python代碼
def print_stack(f=None, limit=None, file=None):
"""Print a stack trace from its invocation point.
The optional 'f' argument can be used to specify an alternate
stack frame at which to start. The optional 'limit' and 'file'
arguments have the same meaning as for print_exception().
"""
if f is None:
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
print_list(extract_stack(f, limit), file)
def print_list(extracted_list, file=None):
"""Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file."""
if file is None:
file = sys.stderr
for filename, lineno, name, line in extracted_list:
_print(file,
' File "%s", line %d, in %s' % (filename,lineno,name))
if line:
_print(file, ' %s' % line.strip())
traceback模塊構造一個ZeroDivisionError,並通過sys模塊的exc_info()來獲取運行時上下文。我們看到,所有的秘密都在tb_frame中,這是函數調用棧中的一個幀。
traceback constructs an ZeroDivisionError, and then call the exc_info() of the sys mole to get runtime context. There, all the secrets hide in the tb_frame, this is a frame of the function call stack.
對,就是這么簡單!只要我們能找到調用棧frame對象即可獲取到行號!因此,我們可以用同樣的方法來達到目的,我們自定義一個lineno函數:
Yes, It's so easy! If only a frame object we get, we can get the line number! So we can have a similar implemetation to get what we want, defining a function named lineno:
python代碼
import sys
def lineno():
frame = None
try:
raise ZeroDivisionError
except ZeroDivisionError:
frame = sys.exc_info()[2].tb_frame.f_back
return frame.f_lineno
def afunc():
# if error
print "I have a problem! And here is at Line: %s"%lineno()
是否有更方便的方法獲取到frame對象?當然有!
Is there any other way, perhaps more convinient, to get a frame object? Of course YES!
python代碼
def afunc():
# if error
print "I have a proble! And here is at Line: %s"%sys._getframe().f_lineno
類似地,通過frame對象,我們還可以獲取到當前文件、當前函數等信息,就像C語音的__FILE__與__FUNCTION__一樣。其實現方式,留給你們自己去發現。
Thanks to the frame object, similarly, we can also get current file and current function name, just like the __FILE__ and __FUNCTION__ macros in C. Debug the frame object, you will get the solutions.
Ⅸ 想用python編寫一個腳本,登錄網頁,在網頁里做一系列操作,應該怎樣實現
python編寫一個腳本的具體操作:
1、首先,打開python並創建一個新的PY文件。
Ⅹ Python 如何寫腳本
以Python2.7操作為例:
1、首先需要打開電腦桌面,按開始的快捷鍵,點擊Python2.7如圖所示的選項進入。