python-markdown用法

markdown工具,可以將txt轉化成html格式。這一類工具的作用是將按一定格式寫成的可讀性強的文本文件
轉化爲結構化的標準xhtml或html。markdown最初用perl寫成,後來移植到python,java,php.這裏主要
介紹下python-markdown的用法。

python-markdown模塊使用有兩個模式,一種是做爲獨立的命令行,另外一種是做爲python的模塊使用。
1. 命令行模式
在Fedora下,命令行名稱是markdown:

[ray@localhost markdown]$ markdown 
Usage: markdown INPUTFILE [options]

Options:
  -h, --help            show this help message and exit
  -f OUTPUT_FILE, --file=OUTPUT_FILE
                        write output to OUTPUT_FILE
  -e ENCODING, --encoding=ENCODING
                        encoding for input and output files
  -q, --quiet           suppress all messages
  -v, --verbose         print info messages
  -s SAFE_MODE, --safe=SAFE_MODE
                        same mode ('replace', 'remove' or 'escape'  user's
                        HTML tag)
  --noisy               print debug messages
  -x EXTENSION, --extension=EXTENSION
                        load extension EXTENSION

使用起來很簡單, 直接運行markdown input.txt > output.html即可。例如:
[ray@localhost markdown]$ cat notes.txt 
Who am I?
===========
This is Ray Chen speaking.

Where am I from?
====================
I'm from SH, China. I love this place.

What's next?
=================
  * nothing
  * sleep
  * study
  * reading book


[ray@localhost markdown]$ markdown notes.txt > notes.html 
[ray@localhost markdown]$ cat notes.html 
<h1>Who am I?</h1>
<p>This is Ray Chen speaking.
</p>

<h1>Where am I from?</h1>
<p>I'm from SH, China. I love this place.
</p>

<h1>What's next?</h1>
<ul>
 <li>
     nothing
 </li>

 <li>
     sleep
 </li>

 <li>
     study
 </li>

 <li>
     reading book
 </li>

2. 模塊用法
[ray@localhost markdown]$ cat test_markdown.py 
#!/usr/bin/python

import markdown
import codecs

# Open input file in read, utf-8 mode
input_file = codecs.open("notes.txt", mode="r", encoding="utf8")
text = input_file.read()
html = markdown.markdown(text)

# print
print html

# Write string html to disk
output_file = codecs.open("notes_py.html", mode="w", encoding="utf8")
output_file.write(html)

[ray@localhost markdown]$ python test_markdown.py 
<h1>Who am I?</h1>
<p>This is Ray Chen speaking.
</p>

<h1>Where am I from?</h1>
<p>I'm from SH, China. I love this place.
</p>

<h1>What's next?</h1>
<ul>
 <li>
     nothing
 </li>

 <li>
     sleep
 </li>

 <li>
     study
 </li>

 <li>
     reading book
 </li>
</ul>
[ray@localhost markdown]$ cat notes_py.html 
<h1>Who am I?</h1>
<p>This is Ray Chen speaking.
</p>

<h1>Where am I from?</h1>
<p>I'm from SH, China. I love this place.
</p>

<h1>What's next?</h1>
<ul>
 <li>
     nothing
 </li>

 <li>
     sleep
 </li>

 <li>
     study
 </li>

 <li>
     reading book
 </li>


後記:
markdown工具在很多程序中用到,比如說wordpress, pybb等,特別適合wiki, blog,forum等。

參考:
http://blog.rogerz.cn/archives/401
http://www.freewisdom.org/projects/python-markdown/



轉自:http://blog.chinaunix.net/uid-7414207-id-2056022.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章