1. 程式人生 > >Python實踐練習:在 Wiki 標記中添加無序列表

Python實踐練習:在 Wiki 標記中添加無序列表

腳本 auth dong com 無序列表 ani board gis run

題目描述

項目:在 Wiki 標記中添加無序列表
在編輯一篇維基百科的文章時,你可以創建一個無序列表,即讓每個列表項占據一行,並在前面放置一個星號。但是假設你有一個非常大的列表,希望添加前面的星號。你可以在每一行開始處輸入這些星號,一行接一行。或者也可以用一小段Python 腳本,將這個任務自動化。
bulletPointAdder.py 腳本將從剪貼板中取得文本,在每一行開始處加上星號和空格,然後將這段新的文本貼回到剪貼板。例如,如果我將下面的文本復制到剪貼板(取自於維基百科的文章“List of Lists of Lists”):
Lists of animals
Lists of aquarium life

Lists of biologists by author abbreviation
Lists of cultivars
然後運行 bulletPointAdder.py 程序,剪貼板中就會包含下面的內容:
* Lists of animals
* Lists of aquarium life
* Lists of biologists by author abbreviation
* Lists of cultivars
這段前面加了星號的文本,就可以粘貼回維基百科的文章中,成為一個無序列表。

運行

命令行運行
復制那四行List

D:\>cd D:\Code\VimCode\Python_auto\Run
D:\Code\VimCode\Python_auto\Run>python bulletPointAdder.py

腳本運行

步驟分析:

1.剪切板的復制和粘貼,使用text=pyperclip.paste(),這個不難,簡單使用pyperclip庫中的.paste()和.copy()就行
2.分離文本中的行,添加星號。line = text.split(‘\n‘)。
3.處理後連結line。text=‘\n‘.join(lines)

代碼:

#! python4
# bulletPointAdder.py - Adds Wikipedia bullet points to the start
# of each line of text on the clipboard.

import pyperclip
text = pyperclip.paste()
# 分離行和添加星號
lines = text.split('\n')
for i in range(len(lines)):
   lines[i] = '*' + lines[i]

# 連結lines
text = '\n'.join(lines)
pyperclip.copy(text)

使用字符串方法總結:

split(str),分離以str為間隔
‘ ‘.join(str),以‘ ‘連接str列表

Python實踐練習:在 Wiki 標記中添加無序列表