Markdown入門基礎


Markdown入門基礎

最近准備開始強迫自己寫博文,以治療嚴重的拖延症,再不治療就“病入骨髓,司命之所屬,無奈何”了啊。正所謂“工欲善其事,必先利其器”,於是乎在寫博文前,博主特地研究了下博文的寫作方式,碰巧發現了Markdown這個神奇的東西。由於博主經常用Latex寫東西,本身就對這類標記語言很有好感,再加上Markdown本身簡單易學的特性,博主一下子就沉浸其中不能自撥了。作為一個准碼農,寫博文的方式怎么着也得跟編碼有關,是不是?在網上找了幾篇教程研究了下,發現這貨雖然簡單,但是文本編輯的基本功能都有,用它寫個博客、記個筆記神馬的完全夠用。最重要的是,這貨上手快啊,只需要個把小時就能把基本功能捋順了。這里對Markdown的入門學習內容做一個簡單地總結,也算是自己的第一篇博文了。另,文中如有不當乃至謬誤,望不吝賜教。(ps 額,你肯定想到了,這篇博文正是用Markdown寫的)


標題

Markdown的標題有Setext和Atx兩種語法格式。
Setext形式中,在文本下面標注=表示最高級標題,在下面標注-表示第二級標題。
Atx形式中,用行首插入的1到6個#分別表示1到6級標題。相比來說,博主還是比較喜歡Atx形式,因為這種形式比較直觀。

以下代碼用Setext形式輸出一級標題和二級標題

Headline 1
==========
Headline 2
----------

其顯示效果如下:

Headline 1

 

Headline 2

以下代碼用Atx形式輸出各級標題:

# Headline 1
## Headline 2
### Headline 3
#### Headline 4
##### Headline 5
###### Headline 6

其顯示結果如下:

Headline 1

Headline 2

Headline 3

Headline 4

Headline 5
Headline 6

當然了,如果你對這種只在行首標記、不在行尾閉合的語法格式不放心的話,也可以在行尾加上任意個#來閉合標題。


段落

Markdown中用空白行來分割段落,這一點與Latex相似。例如以下兩段文本,只需要在兩段之間加一行空行,Markdown就會為文本分段。

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python.

The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.

Markdown使用星號*或下划線_來標記需要強調的區段。其中,一對*_包圍的文字表示斜體顯示,一對雙星號**或雙下划線__包圍的文字表示加粗顯示。

以下代碼可起到區段文字強調的作用

Someofthesewords*areemphasized*.
Someofthesewords_areemphasizedalso_.
Usetwoasterisksfor**strongemphasis**.
Or,ifyouprefer,__usetwounderscoresinstead__.

其輸出如下:
Some of these words are emphasized.
Some of these words are emphasized also.
Use two asterisks for strong emphasis.
Or, if you prefer, use two underscores instead.


字體

有人會問,這貨能改變顏色麽?額,貌似Markdown基本語法不支持任意更改顏色的功能。Markdown的理念是——注重文本本身,特效神馬的交給CSS搞定。當然了,既然這貨支持HTML嵌套,我們可以利用HTML標記實現更改顏色的需求。

更改代碼顏色代碼如下:

Default Color
<font color='red'>Red Color</font>
<font color='blue'>Blue Color</font>
<font color='green'>Green Color</font>
<font color='yellow'>Yellow Color</font>
<font color='pink'>Pink Color</font>
<font color='purple'>Purple Color</font>
<font color='orange'>Orange Color</font>

其輸出為:
Default Color
Red Color
Blue Color
Green Color
Yellow Color
Pink Color
Purple Color
Orange Color

既然可以換顏色了,那換字號、字體也可以用HTML輕松實現了。以下代碼可顯示換字號、字體功能。

<font size='-2'>Small Size</font>
Normal Size
<font size='+2'>Big Size</font>
<font size='+2' face='Times'>Time New Roman</font>

其輸出如下:
Small Size
Normal Size
Big Size
Time New Roman

話說嵌入這些格式化字體的HTML標簽后,整個文本顯得臃腫了不少。這有悖於Markdown注重文本內容、精簡格式化標簽的理念,因此文本特效神馬的,能不用就盡量不用,這些統統扔給CSS去解決,我們只關注文本內容。


引用

Markdown使用email的區塊引用方式,即右尖括號>跟后面的引用內容。下面的代碼為一個引用實例代碼。

>Thismoduleimplementsanumberofiteratorbuildingblocksinspiredby
constructsfromAPL,Haskell,andSML.Eachhasbeenrecastinaformsuitable
forPython.

>Themodulestandardizesacoresetoffast,memoryefficienttoolsthatare
usefulbythemselvesorincombination.Together,theyforman"iterator
algebra"makingitpossibletoconstructspecializedtoolssuccinctlyand
efficientlyinpurePython.

其輸出為:

This module implements a number of iterator building blocks inspired by
constructs from APL, Haskell, and SML. Each has been recast in a form suitable
for Python.

The module standardizes a core set of fast, memory efficient tools that are
useful by themselves or in combination. Together, they form an “iterator
algebra” making it possible to construct specialized tools succinctly and
efficiently in pure Python.


列表

Markdown中使用星號*、加號+和減號-來表示無序列表,以下代碼:

* Apple
* Orange
* Peach
* Banana
+ Apple
+ Orange
+ Peach
+ Banana
- Apple
- Orange
- Peach
- Banana

都可以實現如下功能:

  • Apple
  • Orange
  • Peach
  • Banana

有序列表使用數字加一個英文句點作為項目標記,以下代碼是可以實現一個有序列表。

1. Apple
2. Orange
3. Peach
4. Banana

其輸出如下:

  1. Apple
  2. Orange
  3. Peach
  4. Banana

同時,列表也可以嵌套列表。

1. Fruit
  * Apple
  * Orange
  * Peach
  * Banana
2. Vegetable
  + Potato
  + Cabbage

將輸出:

  1. Fruit
    • Apple
    • Orange
    • Peach
    • Banana
  2. Vegetable
    • Potato
    • Cabbage

另外,列表也可以嵌套引用。

1.itertools

>Thismoduleimplementsanumberofiteratorbuildingblocksinspiredby
constructsfromAPL,Haskell,andSML.Eachhasbeenrecastinaformsuitable
forPython.
>Themodulestandardizesacoresetoffast,memoryefficienttoolsthatare
usefulbythemselvesorincombination.Together,theyformaniterator
algebramakingitpossibletoconstructspecializedtoolssuccinctlyand
efficientlyinpurePython.

2.re

>Thismoduleprovidesregularexpressionmatchingoperationssimilartothose
foundinPerl.

將輸出:

  1. itertools

    This module implements a number of iterator building blocks inspired by
    constructs from APL, Haskell, and SML. Each has been recast in a form suitable
    for Python.
    The module standardizes a core set of fast, memory efficient tools that are
    useful by themselves or in combination. Together, they form an “iterator
    algebra” making it possible to construct specialized tools succinctly and
    efficiently in pure Python.

  2. re

    This module provides regular expression matching operations similar to those
    found in Perl.


鏈接

Markdown支持行內和參考兩種形式的鏈接語法,兩種都是使用中括號來把文字轉成鏈接。

行內形式是中括號包圍文字,后面緊跟圓括號包圍的鏈接,其代碼如下所示:

This is an [example link](http://example.com/).

其輸出為:
This is an example link.

也可以選擇性的給鏈接加上title屬性

This is an [example link](http://example.com/ "With a Title").

效果如下:
This is an example link.

參考形式的鏈接可以在原文中為鏈接定義一個名稱,然后你可以在文章的其他地方定義該鏈接的內容。

以下代碼用於定義鏈接名稱,語法格式為:[鏈接文本][鏈接名稱]

Iget10timesmoretrafficfrom[Google][1]thanfrom
[Yahoo][2]or[MSN][3].

以下代碼用於定義鏈接內容,語法格式為:[鏈接名稱]:空白符 URL "title"

[1]: http://google.com/        "Google"
[2]: http://search.yahoo.com/  "Yahoo Search"
[3]: http://search.msn.com/    "MSN Search"

上面代碼的效果如下:
I get 10 times more traffic from Google than from
Yahoo or MSN.

另外,使用<>包括的URL或郵箱地址會被自動轉換成為超鏈接

<http://example.com/>

<user@example.com>

其效果如下:

http://example.com/

user@example.com


圖片

圖片的語法格式和鏈接類似,也分為行內形式和參考形式。

行內形式語法格式為:![alt text](URL title),alt text和title可以選擇性加入。實例代碼如下:

![額,圖片不能顯示了!](Markdown_basic_files/Markdown_basic_1_0.png"正弦和余弦")

效果如下:

參考形式分為兩部分:聲明圖片鏈接名稱和定義圖片鏈接。

其中,聲明圖片鏈接語法格式為:![alt text][id]

定義圖片鏈接內容的語法格式為:[id]:URL "title"


代碼

在一般段落文字中,可以使用反引號`標記代碼區段。

Istronglyrecommendagainstusingany`<blink>`tags.

IwishSmartyPantsusednamedentitieslike`&mdash;`
insteadofdecimal-encodedentiteslike`&#8212;`.

其效果如下:

I strongly recommend against using any <blink> tags.

I wish SmartyPants used named entities like &mdash;
instead of decimal-encoded entites like &#8212;.

如果是代碼塊的話,那應該怎么插入呢?

在Markdown中,如果行的開頭有4個空格,將被視為代碼。但是這種方式不夠直觀,博主不推薦。博主推薦的方式是代碼塊的的首行用3個反引號```和編程語言名稱(C、CS、Python等,甚至Markdown)標記代碼塊開始,代碼塊的結尾用3個反引號```閉合代碼塊。

例如,將一段Python代碼插入到Markdown中,我們是這樣做的,首行用```Python標記代碼塊,最后一行用```閉合代碼塊,插入代碼如下:

```Python
x = linspace(-pi, pi, 400)
y1 = sin(x)
y2 = cos(x)
plot(x, y1, ‘r’, label=r’$y=\sin x$’)
plot(x, y2, ‘b’, label=r’$y=\cos x$’)
plot([-pi/2, -pi/2], [0, sin(-pi/2)], ‘r–‘)
plot([pi/2, pi/2], [0, sin(pi/2)], ‘r–‘)
xlim(-pi, pi)
legend(loc=’upper left’)
ax = gca()
ax.spines[‘right’].set_color(‘none’)
ax.spines[‘top’].set_color(‘none’)
ax.xaxis.set_ticks_position(‘bottom’)
ax.spines[‘bottom’].set_position((‘data’, 0))
ax.yaxis.set_ticks_position(‘left’)
ax.spines[‘left’].set_position((‘data’, 0))
xticks([-pi, -pi/2, 0, pi/2, pi], [r'$-\pi$', r'$-\frac{\pi}{2}$', 0, r'$\frac{\pi}{2}$', r'$\pi$'])
```

其顯示結果為:

x = linspace(-pi, pi, 400)
y1 = sin(x)
y2 = cos(x)
plot(x, y1, 'r', label=r'$y=\sin x$')
plot(x, y2, 'b', label=r'$y=\cos x$')
plot([-pi/2, -pi/2], [0, sin(-pi/2)], 'r--')
plot([pi/2, pi/2], [0, sin(pi/2)], 'r--')
xlim(-pi, pi)
legend(loc='upper left')
ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
xticks([-pi, -pi/2, 0, pi/2, pi], [r'$-\pi$', r'$-\frac{\pi}{2}$', 0, r'$\frac{\pi}{2}$', r'$\pi$'])

額,忘說了,其實上面插入的正弦余弦圖就是這段Python代碼產生的。

喜聞樂見的Hello World來了!將C代碼插入到Markdown的時候,首行用```C標記,最后一行用```閉合,插入代碼如下:

```C
#include <stdio.h>
void main(int argc, char** argv)
{
    printf(“Hello World”);
}
```

其效果為:

#include <stdio.h>
void main(int argc, char** argv)
{
    printf("Hello World");
}

額,還有C#的實現代碼。將C#代碼插入Markdown的時候,首行用```CS標記,最后一行用```閉合,插入代碼如下:

```CS
using System;
class Program
{
    static void Main(string[] args)
   {
        int argsLength = args.Length;
        Console.WriteLine(“Hello World”));
    }
}
```

其效果為:

usingSystem;
classProgram
{
staticvoidMain(string[]args)
{
intargsLength=args.Length;
Console.WriteLine("Hello World"));
}
}

數學公式

在網頁中插入數學公式是一件很麻煩的事情,比較笨的做法是,在本地用MathType、Latex或者2007版本以后的Office編輯公式,然后截圖,再插入到網頁中。(當然了,你也可以手寫公式,用相機拍照或者用掃描儀掃描圖片,再插入到網頁中。額,這種做法過於文藝范,不在我們的討論范疇中。)比較高端的方法是,把Latex公式代碼上傳到網絡上的Latex服務接口,將其轉換成圖片,然后插入到網頁中。這種方法不用截圖,不用處理圖片,更不用拍照、掃描圖片神馬的,看起來已經夠高大上了吧,但是,但是,我們還有更加高大上的神器。

當當當,接下來隆重地推出我們今天的明星組合:Markdown + MathJax。那么,后面這個新引入的MathJax是個何方神聖呢?

這里(http://mathjax-chinese-doc.readthedocs.org/en/latest/start.html)有一個MathJax的漢化入門指南,感興趣的同學可以看看。

簡而言之,MathJax允許你在你的網頁中包含公式,無論使用$\LaTeX$、MathML或者AsciiMath符號,這些公式都會被javascript處理為HTML、SVG或者MathML符號。由於博主從事的職業需要經常跟$\LaTeX$打交道,所以博主選擇了它編輯公式。

MathJax可以在線用,也可以離線使用。目前,很多Markdown編輯環境都集成了MathJax,比如博主用的IPython Notebook已經內嵌了MathJax;博主用的另一款神器Sublime Text,通過安裝Markdown Preview插件可以實現語法高亮編輯Markdown文件,也可以實時查看渲染結果,把插件配置文件中的”enable_mathjax”屬性設true,便可以用MathJax渲染數學公式。有了這些工具的背后支持,可以使我們只需要專注於文章內容本身,而不用去考慮內容具體是怎么格式化的,公式具體是怎么渲染的。

以下,通過幾個$\LaTeX$公式例子講解一下Markdown中如何插入數學公式。當然了,這里不會仔細講解$\LaTeX$語法,這貨不是一篇博文就能搞定的。

如果有對$\LaTeX$感興趣的同學,這里(http://www.ctex.org/OnlineDocuments)有不少在線資料可以參考一下。

Markdown支持直接內嵌$\LaTeX$公式,例如以下代碼可以插入行內公式:

正弦函數$sin\,x$</code>$\frac{\pi}{2}$點可以取得極大值點1,周期性使得極大值點有無數個,即正弦函數的極大值點為:$\sin(\frac{\pi}{2}+2n\pi)=1,\quad n=0,\pm1,\pm2, \dots$

其輸出為:
正弦函數$sin\,x$在$\frac{\pi}{2}$點可以取得極大值點1,周期性使得極大值點有無數個,即正弦函數的極大值點為:$\sin
(\frac{\pi}{2}+2n\pi)=1,\quad n=0,\pm 1, \pm 2, \dots$

例如,以下代碼可以給出一個行間公式:
$$g(x,y)=\frac{1}{2\pi\sigma^2}e^{-\frac{x^2+y^2}{2\sigma^2}}$$

其輸出為:
$$g(x,y)=\frac{1}{2\pi\sigma^2}e^{-\frac{x^2+y^2}{2\sigma^2}}$$


例子

接下來,博主要展示幾個寫筆記的小例子,這些筆記都是用Markdown + MathJax + Latex + Python + matplotlib + IPython Notebook生成的。看完這些筆記的效果,相信大家會認識到Markdown與這些工具組合后的強大生產力。

例子一 正態分布

from pylab import *
x = linspace(-8, 8, 400)
sigma = 0.5
u = 0
y = 1/sqrt(2*pi*sigma)*exp(-(x-u)**2/(2*sigma))
plot(x, y, 'r', label=r'$\sigma^2=0.5\quad \mu=0$')
sigma = 1
y = 1/sqrt(2*pi*sigma)*exp(-(x-u)**2/(2*sigma))
plot(x, y, 'g', label=r'$\sigma^2=1\quad \mu=0$')
sigma = 5
y = 1/sqrt(2*pi*sigma)*exp(-(x-u)**2/(2*sigma))
plot(x, y, 'b', label=r'$\sigma^2=5\quad \mu=0$')
u = 2
sigma = 2
y = 1/sqrt(2*pi*sigma)*exp(-(x-u)**2/(2*sigma))
plot(x, y, 'k', label=r'$\sigma^2=1\quad \mu=0$')

legend(loc='upper left')
ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

將輸出:

若隨機變量$X$服從一個位置參數為$\mu$,尺度參數為$\sigma$的概率分布,可記為:
$$X \sim \mathcal{N}(\mu, \sigma^2)$$
其概率密度函數為:
$$f(x) = \frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$$
正態分布的數學期望值$\mu$等於位置參數,決定了分布的位置,其方差$\sigma^2$的開平方或標准差$\sigma$等於尺度參數,決定了分布的幅度。正態分布
的概率密度函數曲線如上上圖所示。

例子二

from pylab import *
from mpl_toolkits.mplot3d import Axes3D
sigma = 5
fig = figure()
ax = Axes3D(fig)
r = linspace(0, 15, 50)
t = linspace(0, 2*pi, 30)
R, T = meshgrid(r, t)
X, Y = R*cos(T), R*sin(T)
Z = -((X*X + Y*Y-2*sigma**2)/(sigma**4))*exp(-(X*X + Y*Y)/(2*sigma**2))
ax.plot_surface(X, Y, Z, rstride=3, cstride=3, color='green')

將輸出:

$$\triangledown^2 g(x,y)=\frac{x^2+y^2-\sigma^2}{\sigma^4}e^{-\frac{x^2+y^2}{2\sigma^2}}$$
其中
$$x=R\cos \theta,\;y=R\sin \theta \quad R\in[0,15],\;\theta\in[0, 2*\pi]$$
傳說中的“墨西哥草帽”,相信做圖像處理的同學應該不會陌生。

例子三 斐波那契數列和黃金分割

斐波那契數列是一個特殊的數列,它的當前項等於前兩項之和,即$A_n=A_{n-1}+A_{n-2}$。那么,斐波那契數列又跟黃金分割有神馬聯系呢?經研究發現,前后相鄰的兩個斐波那契數的比值隨着序號的增加而逐漸趨向於黃金分割比,即
$$\lim_{n\to \infty}\frac{A_{n-1}}{A_n}=\frac{\sqrt{5}-1}{2}.$$

以下代碼首先產生一個斐波那契數列,然后求出數列中前后相鄰兩項的比值,最后描繪出相鄰兩項比值的變化趨勢圖。

from pylab import *
fib = [1, 1]
for i in range(40):
    fib.append(fib[-1]+fib[-2])
ratio = []
for i in range(1, len(fib)):
    ratio.append(float(fib[i-1])/fib[i])
plot(ratio, label='Fibonacci Ratio')
golden_ratio = (sqrt(5) - 1)/2
plot(range(len(fib)), [golden_ratio]*len(fib), 'r--', label='Golden Ratio')
ylim(0, 1.1)
legend()
annotate(r'$\frac{\sqrt{5}-1}{2}$', xy=(15, golden_ratio),  xycoords='data',
         xytext=(10, 50), textcoords='offset points', fontsize=16, color='red',
         arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2', color='red'))

將輸出:

上圖中,藍線為斐波那契數列前項與后項的比值,紅線表示黃金分割比的倒數。可以看出,隨着斐波那契數列項數的不斷增加,數列中前后兩項的比值逐漸收斂到黃金分割比例。


參考

  1. Markdown 語法說明 (簡體中文版)
  2. MathJax 中文文檔
  3. Latex 文檔
  4. IPython Notebook
  5. matplotlib
  6. Sublime Text
  7. Sublime Text 2/3 Markdown Preview


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM