谷歌拼音输入法的化学专业词典

简介

可以用于谷歌输入法的词典文件,包含大量中文化学词汇,多为化合物名称。词库容量很大,有15976条化合物名称中文词汇;包括各种多音字拼写(也包括拼错的)共有拼音条目6万余条。比较搜狗拼音化学词汇大全【官方推荐】的一千多条的量要大多了。

google pinyin dict for chemist

作者 zh.charlie@gmail.com

使用方法

在谷歌拼音输入法的“属性设置”中导入

googlepinyinimport.png

数据和制作方法

化合物中文名称,从Chemblink.com网站上采样获得。

词汇提取程序使用Python编写。其中,从unicode字符串中提取汉字的正则表达式:

ur'([\u4e00-\u9fa5]+)'

汉字到拼音的转换程序,使用了roy在水木上贴的python代码和数据库

谷歌拼音输入法的词典格式和分析方法,在前一篇中有所介绍。

使用授权

随便用。随意转载、修改、使用,不必注明原作者。对词典的正确性、全面性作者无法保证和负责。


下载

google.pinyin.dict.for.chemists.zip

自动单元测试框架, PyUnit, tsqlunit, xUnit framework

Notes on Python自动单元测试框架

from widget import Widget
import unittest

class WidgetTestCase(unittest.TestCase):                   # 测试例(test case)
    def setUp(self):                                       # 测试前的初始化工作。
                                                           # 声明在unittest.TestCase中,自动调用。
        self.widget = Widget()
    def tearDown(self):                                    # 测试后的清理工作。
        self.widget = None

    def testSize(self):                                    # 自定义的测试方法。
        self.assertEqual(self.widget.getSize(), (40, 40))  # assertEqual是TestCase提供的工具。

    def testColor(self):                                   # 一个测试例中可以定义多个测试方法函数。
                                                           # 默认的测试方法函数名为runTest
        pass

def suite():                                               # 测试集(test suite)
    suite = unittest.TestSuite()                           # 函数返回TestSuite的测试集实例。
    suite.addTest(WidgetTestCase("testSize"))              # 测试集中加入测试方法。
                                                           # 多个测试方法组成一个测试集。
                                                           # 可以用unittest.makeSuite批量添加测试方法。
    return suite

if __name__ == "__main__":
    unittest.main(defaultTest = 'suite')                   # 执行测试
                                                           # 也可自定义执行测试的Runner
                                                           #     runner = unittest.TextTestRunner()
                                                           #     runner.run(suite)

自动生成测试例,批量测试

借鉴JUnit框架上的一个方案,用程序生成一个足够大的测试集。Write a suite( ) method that iterates through all of your
input data, creating a unique instance of your test case for each
unique input. The data is passed to the test cases through the
constructor, which stores the data in instance fields so it is
available to the test methods.

A similar solution,
pyUnit and dynamic test functions .

如果像我这样需要一个测试集,可以自动的无穷尽的pop出各种各样的,甚至是随机的测试例,或者是测试例的参数,而不是预先在测试集中(内存中)建立好所有的测试例,可以利用TestSuite的Iterator的特性实现。

TestRunner中的run方法,对TestSuite来说,仅仅是调用了其test方法。

class TextTestRunner:
    """ ... """
    def run(self, test):
        "Run the given test case or test suite."
        result = self._makeResult()
        startTime = time.time()
        test(result)
        stopTime = time.time()
        timeTaken = stopTime - startTime
        result.printErrors()
    """ ... """

所以可以重载TestSuite类,生成支持Iterator的测试集,自动生成测试例。代码如下

import unittest
class TheTestCase(unittest.TestCase):
    def __init__(self, n):
        unittest.TestCase.__init__(self)
        self.n = n
    def runTest(self):
        assert( self.n>3 )

class MyTestSuite(unittest.TestSuite):
    def __init__(self):
        unittest.TestSuite.__init__(self)
        self.i = 0
        self.N = 5
    def __iter__(self):
        return self

    def next(self):
        self.i += 1
        if self.i > self.N: raise StopIteration
        return TheTestCase(self.i)

    def run(self, result):
        for test in self:
            if result.shouldStop:
                break
            test(result)
        return result

def suite():
    return MyTestSuite()

if __name__=='__main__':
    unittest.main(defaultTest='suite')

xUnit Framework

结合这个tsqlunit框架 (不是很实用),可以粗略总结xUnit Framework构建的单元测试框架里的一些要点。

  • 集中格式化输出显示(PRINT)测试结果及报告。
  • 通过测试集、测试例组织管理测试代码,重用测试代码。
  • 自动加载测试例。
  • 统一测试例的接口(包括异常抛出),简化测试例编写。

Setup Web.py and flup on Windows+Apache(WAMP)

  • Web.py is installed by “Easy Install” as Python eggs.
  • To install “Easy Install”(setuptools), download ez_setup.py, run it, setuptools egg for right Python version is installed automatically.
  • Run “ez_setup.py web.py”, web.py is installed automatically.
  • web.py implements WSGI. Need to install flup to provide WSGI interfaces for web.py and web server as CGI, FastCGI or SCGI.
  • Config Apache to allow CGI on web directory. Most common problem is permission setting, but its fare easy on Windows.
  • Problem exists with flup to run under such environment. Blow logs could be found in Apache err log

[Thu Sep 27 09:21:34 2007] [error] [client 127.0.0.1] File “D:\Python25\lib\site-packages\flup-1.0-py2.5.egg\flup\server\fcgi_base.py”, line 976, in _setupSocketr
[Thu Sep 27 09:21:34 2007] [error] [client 127.0.0.1] AttributeError: ‘module’ object has no attribute ‘fromfd’r
[Thu Sep 27 09:21:34 2007] [error] [client 127.0.0.1] Unhandled exception in thread started by r
[Thu Sep 27 09:21:34 2007] [error] [client 127.0.0.1] Error in sys.excepthook:r

Solved referencing to http://groups.google.com/group/webpy/browse_thread/thread/67a8cfa5fdb1882b/722acab404514de4
Modification to flup code and repack is needed.

Down load flup code (but by ez_setup).
Modify fcgi_base.py as:

    def _setupSocket(self):
        if self._bindAddress is None: # Run as a normal FastCGI?
            isFCGI = True

            #@ commented by charlie, ref: http://groups.google.com/group/webpy/browse_thread/thread/67a8cfa5fdb1882b/722acab404514de4
##             sock = socket.fromfd(FCGI_LISTENSOCK_FILENO, socket.AF_INET,
##                                  socket.SOCK_STREAM)
##             try:
##                 sock.getpeername()
##             except socket.error, e:
##                 if e[0] == errno.ENOTSOCK:
##                     # Not a socket, assume CGI context.
##                     isFCGI = False
##                 elif e[0] != errno.ENOTCONN:
##                     raise
            isFCGI = False

            # FastCGI/CGI discrimination is broken on Mac OS X.

Rebuild eggs for flup following the easy instructions, run “setup.py bdist_egg“.
Copy the new egg to site-packages directory.

My things done.

Python 2.5 发布,支持Conditional Expressions

曾经笔记过用 and 和 or 来实现 Conditional Expressions。在刚发布的Python 2.5版已经明确的实现了这个功能

可以这样用了:
x = true_value if condition else false_value

当然,这只是Python 2.5 众多新特性中不起眼的一个吧。

四色立方体问题

Davies大侠那里看到这个问题。这个问题是Thumbjive招聘工程师时要求随简历要一同提交。去年春天我还没毕业时,也解了这个问题,并且去Thumbjive面试了。当时也是用Python解的,面试我的法国工程师还很高兴我懂Python这个东西。实际上当时刚刚接触Python,现在看起来当时写的代码,实在是太不Python style了。

参考Davies的解法,总结一下这个问题的解决过程。

原题在Thumbjive网站的招聘页面中。

You have four colored cubes. Each side of each cube is a single color, and there are four colors: blue (B), red (R), green (G) and yellow (Y) Describing the six faces as front, back, left, right, top, bottom, the cube colors are:

Cube
Front
Back
Left
Right
Top
Bottom
1
R
B
G
Y
B
Y
2
R
G
G
Y
B
B
3
Y
B
R
G
Y
R
4
Y
G
B
R
R
R

The objective is to find ways to stack the four cubes as a vertical column so that each side of the column is showing all four colors.

有四个立方体,每个有六个面,涂上了四种颜色。要求摞成一个长条,并使其四个侧面都有四种不同的颜色。

我想这里主要要解决两个事情:

  1. 立方体的表示。包括对其运动(旋转)的描述。并且要有一个描述立方体所有可能位置的集合,很容易看出每个立方体有24种可能的位置。
  2. 对四个立方体所有可能位置进行排列,找出满足要求的排列。

对于1,Davies定义了两个立方体的动作,侧面转一圈和翻个。 然后汇成一个角的三个面作为初始状态,分别翻个,转一圈。正好得到了24种可能位置。比我当时考虑的强,我定义了x,y轴两个方向的旋转,并且用这两个动作连续旋转立方体,虽然能遍历所有的状态,但是显然有冗余。

我定义的旋转遍历:


# a serial of cube rotation
# make sure that the cube placed in all possible position
all_seq = [2,1,1,1,1, # following with 4 transform 1 means unchanged
2,1,1,1,1,
2,1,1,1,1,
2,1,1,1,1, # no position change
1,2,
1,1,1,1,
1,1,
1,1,1,1]

对于2,Davies枚举了所有可能排列,应该是一种宽度优先算法吧。如果只要求得到一个解,而不给出所有解的前提下,深度优先搜索能更快。不过我原来的脚本写得太滥了,运行速度明显慢很多。于是在他的脚本基础上,我写了个深度优先的算法solve2,可以代替Davies的solve来用。


def solve2(belows, aboves=[[]]):
”’ 060805, charlie, depth first solution ”’
belows = [b for b in belows] # copy object as a ‘pass-by-value’ argu of function
nodes = combine(aboves, turn(belows.pop(0)))
if not nodes: return False
if not belows: return nodes # all cubes placed
return reduce( lambda x,n: x or solve2(belows, [n]),
nodes , False )

实际效果上也没快多少,可能是搜索树的深度比较浅,没啥效果吧。

另外有写得不好的地方,就是搞不懂pass-by-value传参应该怎么弄比较好;和找不到一个代替逻辑运算符or的函数, 只好lambda了一个。

最后贴一下去年我写的脚本,不值得一看,权且留念。

(more…)

Python中的and和or

Python 中的逻辑运算,and 和 or 并不是像c/c++类的语言一样,返回 true或者 false。他们的返回值(return value)是两个操作符(operantor)中,其中一个的值。

这个特点似乎在同是脚本语言的lua中也是一样。有人还认为这不太正常,有点气愤

实际上这种设计还是很合乎逻辑的,也有用处。比如以前我曾经不解类似c语言中 condition?a:b 这种语句在python中的写法,在水木上得到指教,用 and 和 or 就可以很简洁地表达出来

r = cond and x or y

Python 2.4文档的 5.10 中也提到了:

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or ‘foo’ yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not ‘foo’ yields False, not ”.

举的例子是:“如果为空(非法值、失败)的话就使用默认值”,简洁的表达。

所以这里的 x and y 可以理解为:先x,“然后再” y。是不是让 and 这个词回归本来的语义了呢?

同理,x or y就是:如果x 不成的话,y (为真)也行啊。

如果上面的 x, y 都是函数的话,x or y or z… 就是 “从左到右执行这些操作,直到其中一个成功为止” 。 x and y and z… 就是“从左到右执行这些操作,有一个失败就拉倒”。

如果 and 和 or 组合起来,意思就更丰富了。

这不正是脚本语言所追求的吗? 不能从c/c++的角度来理解脚本语言

Python中的r = cond?x:y(转寄)

发信人: Black8 (⑧), 信区: Python
标 题: Python中的r = cond?x:y
发信站: 水木社区 (Tue Feb 7 22:47:08 2006), 转信

c语言中的这个语法,
如果cond=True,r = x 否则 r = y

在Python中有没有相应的表达方法?

我大概实验了一下,下面这个写法也可以:

r = cond and x or y

发信人: ghc (sunnavy), 信区: Python标 题: Re: Python中的r = cond?x:y发信站: 水木社区 (Tue Feb 7 23:12:16 2006), 转信
那样写不好,比如:

1?0:3 // get 01 and 0 or 3 # get 3

发信人: redhair (lolicon), 信区: Python标 题: Re: Python中的r = cond?x:y发信站: 水木社区 (Tue Feb 7 23:51:03 2006), 转信

r = (cond and [x] or [y])[0]

发信人: hotdog9 (每天爱你多一些), 信区: Python标 题: Re: Python中的r = cond?x:y发信站: 水木社区 (Wed Feb 8 10:25:54 2006), 转信

[y,x][bool(cond)]

Operation result by-Value or by-Reference [Python]

对一个对象的操作使这个对象有所变化。
这种情况很常见,比如“去除一个list的后三个元素”。
我首先想到的方法是:

>>> a = [1,2,3,4,5,6,7]
>>> a = a[:-3]
>>> a
[1, 2, 3, 4]
>>>

这样的确能使a得到想要的改变,但实际上a“已经不是原来那个a”了。

>>> id(a)
20363584
>>> a = a[:-3]
>>> id(a)
20365224

a所代表的对象已经不同。id函数可以得到对象的标识(identify),从而区别不同对象。

这种情况有时会产生很致命的错误。比如a作为参数传递给一个函数,因为Python的函数参数调用是“引用传值,pass-by-reference”的,所以可能希望函数内对a的操作影响到函数外a对象,这时上面的情况就会发生错误。
正是这个错误耽误了我半天的时间来debug。
针对不同的对象,解决这个的问题方法不同。仅对这里提出的问题做个正解:

>>> a = [1,2,3,4,5,6,7]
>>> id(a)
14198904
>>> del a[-3:]
>>> id(a)
14198904
>>> a
[1, 2, 3, 4]

这个问题的最根本问题其实出在

>>> a = a[:-3]

这句。“=”默认的意思是“赋值,pass the value”,不是传递对象的引用。

list partterns in Matlab and Python

list partterns in Matlab and Python

A comparation between usage in Matlab against Python of the List variable as the most common and frequently utility in the languages.

Indexing

Key point of Indexing: Index, List to be filtered
Matlab

>> lst = rand(2,3) %@ the List to be filtered
lst =
0.4103 0.0579 0.8132
0.8936 0.3529 0.0099

>> i = lst > 0.5 %@ the Index, a list with integer elements
i =
0 0 1
1 0 0

>> lst(i) %@ the Result, get a new list from lst with elements indexed by i
ans =
0.8936
0.8132

>> lst(lst>0.5)=1
lst =
1.0000 0.0579 1.0000
1.0000 1.0000 0.0099

Append

Python

lst.append(obj)

Matlab
No declaration or additional appending operation.

>> clear
>> lst(2) = 1
lst =
0 1

>> lst(5) = 1
lst =
0 1 0 0 1

>> lst(length(lst)+1) = 9 %@ Appending operation
lst =
0 1 0 0 1 9

Sorting

>> lst=rand(3,4)
lst =
0.9501 0.4860 0.4565 0.4447
0.2311 0.8913 0.0185 0.6154
0.6068 0.7621 0.8214 0.7919
>> sort(lst) %@ Matrix sorting means “Sorts each column”.
ans =
0.2311 0.4860 0.0185 0.4447
0.6068 0.7621 0.4565 0.6154
0.9501 0.8913 0.8214 0.7919
>> sortrows(lst,1) %@ Each row treated as a element in List.
ans =
0.2311 0.8913 0.0185 0.6154
0.6068 0.7621 0.8214 0.7919
0.9501 0.4860 0.4565 0.4447

Test Zoundry

A test of Zoundry. Noticed that it’s built up by Python. A Tag could be added and what will happen?

Del.icio.us :

Next Page »

Random posts

  • 有人扒我的网站
  • 推荐8box的音乐专题:在忧伤的旋律中的情人节
  • 读一段论语
  • 积水潭医院回龙观院区
  • 中关村企业篮球赛,亚军