Python String

0 意見

Writing Python Scripts in Unicode

# -*- coding: utf-8 -*-

String Literals

# normal string
"Either single or double quotes can be used to quote strings."
'Either single or double quotes can be used to quote strings.'

# raw string
r"C:\Python26\README.txt"

# multiline string
txt = """
This is a multiline string literal
enclosed in triple double quotes.
"""

txt = '''
And this is a multiline string literal
enclosed in triple single quotes.
'''

# string formatting expressions
width = 80
height = 40
msg = "the size is %d x %d" % (width, height)

Basic String Operations

str = r"C:\Python26\README.txt"

# remove whitespace
str = str.rstrip()

# string length
len(str)

# fetch the last 4 characters
str[-4:] #>>> '.txt'

# end test
str.endswith(".txt")

# Split the string at the last occurrence of sep
str.rpartition("\\") #>>> ('C:\\Python26', '\\', 'README.txt')

Parsing a Text File

txtfile = open(r"C:\Python26\README.txt", "rt").readlines()
searchterm = ['python', 'documentation']
for ln, Line in enumerate(txtfile):
    lline = Line.lower()
    word_list = lline.split()
    for term in searchterm:
       if term in word_list:
          col = lline.index( term )
          print "Found '%s' in %d:%d" %(term, ln+1, col+1), Line,

Regular Expression

import re

txt = open(r"C:\Python26\README.txt", "rt").read()
emails = re.findall('[a-zA-Z0-9+_-.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', txt)
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', txt)

print "emails=", emails, "\n"
print "urls=", urls, "\n"
Extract the title of a html page
import urllib, re

page = urllib.urlopen('http://www.google.com').read()
title = re.findall('(.*)', page)
print title

glob Module

import glob

searchterm = ['python', 'documentation']
files = glob.glob(r"C:\Python26\*.txt")

for filename in files:
    fh = open(filename, "rt")
    txt = fh.readlines()
    for ln, Line in enumerate(txt):
        lline = Line.lower()
        for term in searchterm:
            num_matches = lline.count(term)
            if num_matches:
                 print "found '%s' %d times in %s on line %d." % (term, num_matches, filename, ln+1)

    fh.close()

Read/Write a Unicode Text File

import codecs
f = codecs.open("test.txt", "r", "utf-8")

Reference

Python easy_install

0 意見
讓 Python 安裝模組變得很簡單。
以安裝 lxml 為例:

D:\>easy_install lxml
Searching for lxml
Best match: lxml 2.2.2
Processing lxml-2.2.2-py2.6-win32.egg
lxml 2.2.2 is already the active version in easy-install.pth

Using c:\python26\lib\site-packages\lxml-2.2.2-py2.6-win32.egg
Processing dependencies for lxml
Finished processing dependencies for lxml

升級 docutils

D:\>easy_install --upgrade docutils
Searching for docutils
Reading http://pypi.python.org/simple/docutils/
Reading http://docutils.sourceforge.net/
Best match: docutils 0.8.1
Downloading http://prdownloads.sourceforge.net/docutils/docutils-0.8.1.tar.gz?do
wnload
Processing docutils-0.8.1.tar.gz
Running docutils-0.8.1\setup.py -q bdist_egg --dist-dir c:\users\daniel.lin\appdata\local\temp\easy_install-ylkkgr\docutils-0.8.1\egg-dist-tmp-vfxzir
"roman" module already present; ignoring extras/roman.py.
warning: no files found matching 'MANIFEST'
warning: no previously-included files matching '.cvsignore' found under director y '*'
warning: no previously-included files matching '*.pyc' found under directory '*' 
warning: no previously-included files matching '*~' found under directory '*'
warning: no previously-included files matching '.DS_Store' found under directory  '*'
zip_safe flag not set; analyzing archive contents...
docutils.parsers.rst.directives.misc: module references __file__
docutils.writers.html4css1.__init__: module references __file__
docutils.writers.latex2e.__init__: module references __file__
docutils.writers.odf_odt.__init__: module references __file__
docutils.writers.pep_html.__init__: module references __file__
docutils.writers.s5_html.__init__: module references __file__
Adding docutils 0.8.1 to easy-install.pth file
Installing rst2html.py script to C:\Python26\Scripts
Installing rst2latex.py script to C:\Python26\Scripts
Installing rst2man.py script to C:\Python26\Scripts
Installing rst2odt.py script to C:\Python26\Scripts
Installing rst2odt_prepstyles.py script to C:\Python26\Scripts
Installing rst2pseudoxml.py script to C:\Python26\Scripts
Installing rst2s5.py script to C:\Python26\Scripts
Installing rst2xetex.py script to C:\Python26\Scripts
Installing rst2xml.py script to C:\Python26\Scripts
Installing rstpep2html.py script to C:\Python26\Scripts

Installed c:\python26\lib\site-packages\docutils-0.8.1-py2.6.egg
Processing dependencies for docutils
Finished processing dependencies for docutils

安裝 sphinx

D:\>easy_install sphinx
Searching for sphinx
Best match: sphinx 1.1
Processing sphinx-1.1-py2.6.egg
sphinx 1.1 is already the active version in easy-install.pth
Installing sphinx-apidoc-script.py script to C:\Python26\Scripts
Installing sphinx-apidoc.exe script to C:\Python26\Scripts
Installing sphinx-apidoc.exe.manifest script to C:\Python26\Scripts
Installing sphinx-build-script.py script to C:\Python26\Scripts
Installing sphinx-build.exe script to C:\Python26\Scripts
Installing sphinx-build.exe.manifest script to C:\Python26\Scripts
Installing sphinx-quickstart-script.py script to C:\Python26\Scripts
Installing sphinx-quickstart.exe script to C:\Python26\Scripts
Installing sphinx-quickstart.exe.manifest script to C:\Python26\Scripts
Installing sphinx-autogen-script.py script to C:\Python26\Scripts
Installing sphinx-autogen.exe script to C:\Python26\Scripts
Installing sphinx-autogen.exe.manifest script to C:\Python26\Scripts

Using c:\python26\lib\site-packages\sphinx-1.1-py2.6.egg
Processing dependencies for sphinx
Finished processing dependencies for sphinx

官方網站:http://peak.telecommunity.com/DevCenter/EasyInstall

volatile,多緒和最佳化

0 意見
在多執行緒的情況下,考慮下面的程式碼 :

x =  0;
lock();
x++;
unlock();

一般來說,我們會認為有了 lock 和 unlock 的保護,變數 x 在多緒的環境下會被正常的累加。但如果我們把最佳化的影響考慮進來,情況就不如我們一開始所想的那麼地的單純。一般常見的最佳化做法如下:

  1. 編譯器為了提高變數 x  的存取速度而把 x 放到了某個 register 裡。
  2. 編譯器為了提高效率而交換指令執行的順序。
  3. CPU 的動態排程,為了提高效率而交換指令執行的順序。

以第一種情形來說,不同的執行緒的 register 是各自獨立的,若編譯器在 lock 之前就先把 x 放到 某個 register 裡,並因之後可能還要存取 x 而暫時不將 register 內的值寫回 x ,那麼很明顯就會有問題。針對編譯器過度最佳化的解決方法是使用關鍵字 volatile 提示編譯器考慮多緒執行的情況,不要進行如上的最佳化。

關鍵字 volatile 表示變數可能會被某些編譯器未知的因素更改 (如 I/O),所以每次要存取 volatile 變數時,必須從記憶體中重新讀取值。

而關於 3. CPU 的動態排程的影響,我們可以使用 CPU 所提供的 barrier 指令 (在不同 CPU 中指令名稱各不相同),來保證緒程安全。一般我們常使用的同步函式如 mutex 或 semaphore 等都有使用 barrier 來實作 。

Reference

Windows 網路芳鄰分享更換帳號登入作法

0 意見
相信被這個問題困擾的人不少。我也是困擾了一段時間,今天終於找到解答,記錄一下:

將所有輸入過的驗證 cache 清除
C:\> net use * /del /y

直接給連線帳號
C:\> net use /user:xyz \\192.168.12.129\worktemp

參考資料