Pages

Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Feb 6, 2016

Execute python code using ./

Step1: add #!/usr/local/bin/python in the first line of the code
Step2: in the bash, type chmod +x myscript.py
Step3: type ./myscript.py to execute the python code

Jul 19, 2015

Use Sphinx to automatically create Python documents

Creating program documents is a tedious task. However, with the assistance of automatic tools for creating program documents, we can produce the documents in a very easy and quick way. (We still have to write the comments of program functions.)

Here are the steps of that I used Sphinx to create documents for my python project.

1. Install Sphinx
$ pip install sphinx 


2. Create a directory (folder) for documents
Create a directory named "docs", and the structure of the "docs" and "src" directories is shown below:

Python Project/
  |--------docs/
  |--------src/(source code)


3. Create a Sphinx project
In the docs/ directory, perform the following command:
$ sphinx-quickstart docs


During the process, you will be asked several questions. The following are my answers to some of the questions (empty answer means using the default setting):

Separate source and build directories (y/n) [n]: y
autodoc: automatically insert docstrings from modules (y/n) [n]: y
intersphinx: link between Sphinx documentation of different projects (y/n) [n]: y
ifconfig: conditional inclusion of content based on config values (y/n) [n]: y
viewcode: include links to the source code of documented Python objects (y/n) [n]: y

After step 3 is finished, the structure of the Sphinx project will be that as follows:
Python Project/
  |--------docs/
  |             |----- build
  |             |----- source
  |--------src/(source code)


4. Modify docs/source/conf.py
In the conf.py file created in step 3, find the following comments.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

Add a setting under the above comments so that Sphinx can find the source code.
sys.path.insert(0, os.path.abspath('../../src/'))


5. Use sphinx-apidoc to create module_name.rst files
$ sphinx-apidoc -o docs/source src


6. Create html files
In the docs directory, perform the following command to create the documents' html files.
$ make html

If the documents are successfully created, you can open the docs/build/html/index.html to read it.


Reference:
http://chimerhapsody.blogspot.com/2014/07/python.html
http://sphinx-doc.org/invocation.html#invocation-of-sphinx-apidoc




Jun 24, 2015

Import a module from your package in Python

If I have two modules in two packages in the same folder described below:
myfolder/
        package1/
                __init__.py  (need to add an empty file)            
                module1.py (has a function test())
        package2/
                __init__.py
                module2.py

I can use the following code in module2 to import module1

Jun 1, 2015

Output data to csv files

There is a little difference between the code implemented in Python 2 and 3.

May 28, 2015

[Python] Don't use "<<" to double a number

As we know, we can use "a << b" to represent "a*(2^b)." But this method is much slower than just using addition, performing "a+=a" for b times. In other words, "<<" operation is much more expensive than "+" operation.

I have performed some simple experiments. The results are shown below.


As we can see, the running time for "<<" operations are much slower than that of "+" operation. It takes more than several hundred times for "<<" to produce the same result as "+" does. Therefore, using "+" operation instead of using "<<" for the same purpose. (Here I am under the restriction of not using multiplication.)

May 18, 2015

May 12, 2015

Call by assignment in Python

When passing a mutable object (list, dictionary, etc.) to a function, it works like "call by reference" that the object will be shared.

When passing a immutable object (int, tuple) to a function, it works like "call by value" that it pass a copy of the original object to a function.

See more detail:
[1] https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference
[2] http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference

Apr 22, 2015

[Python] A simple way to sort a dictionary

[Python] An example of scraping date from a website and writing to a csv file

In order to scrape data from a website, I used the "BeautifulSoup" module for Python. The data I want to get from the website (http://www.charitynavigator.org/index.cfm?bay=topten.detail&listid=24#.VTfpxa3BzGc) is the "10 Super-Sized Charities."



A sample code is shown below:
And the result is

Apr 16, 2015

[Python] defaultdict will not always generate default value

If you didn't assign default data type, then the defaultdict will not generate a default value for a missing key. For this case, we can use get(key) to find the key value and it will not cause error if the key is missing. See the following example.

Apr 4, 2015

[Python] Counter

The function of "Counter" make it very convenient to count the number of repeated items in two list. See the following example.

Apr 3, 2015

[Python] some operations on list

When using a list in Python, we can see the indicator of the items as follows:
x = [0, 1, 2, 3, 4, 5, 6, 7, 8]
x[0],   x[1],   x[2],   x[3],   x[4],   x[5],   x[6],   x[7],   x[8]
x[-0],  x[-8], x[-7],  x[-6],  x[-5], x[-4],  x[-3],  x[-2], x[-1]   <= reverse direction
x[-9]
some usages of list in Python are shown below:

Mar 24, 2015

[Python] strip vs. replace

Here are some examples showing the differences between the function of "strip()" and "replace()" in Python.
Be careful! strip() will delete any character in the beginning or end of the word that matches "any" character in the word we put in the strip function. For example, we put "& quot;" as a parameter into strip(), then any character matches ('&', 'q', 'u', 'o', 't', ';') will be deleted. It doesn't have to be exactly the same "string."