Python实践练习:在 Wiki 标记中添加无序列表

题目描述

项目:在 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:CodeVimCodePython_autoRun
D:CodeVimCodePython_autoRun>python bulletPointAdder.py

脚本运行

步骤分析:

1.剪切板的复制和粘贴,使用text=pyperclip.paste(),这个不难,简单使用pyperclip库中的.paste()和.copy()就行
2.分离文本中的行,添加星号。line = text.split(' ')。
3.处理后连结line。text=' '.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('
')
for i in range(len(lines)):
   lines[i] = '*' + lines[i]

# 连结lines
text = '
'.join(lines)
pyperclip.copy(text)

使用字符串方法总结:

split(str),分离以str为间隔
' '.join(str),以' '连接str列表

原文地址:https://www.cnblogs.com/wudongwei/p/8986747.html