当前位置:嗨网首页>书籍在线阅读

23-第2步_分离文本中的行,并添加星号

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

第2步:分离文本中的行,并添加星号

调用 pyperclip.paste() 函数将返回剪贴板上的所有文本,结果是一个大字符串。如果我们使用“List of Lists of Lists”的例子,保存在 text 中的字符串就像这样:

'Lists of animals\nLists of aquarium life\nLists of biologists by author
abbreviation\nLists of cultivars'

在输出到剪贴板或从剪贴板粘贴时,该字符串中的 \n 换行符让它能显示为多行。在这一个字符串中有许多“行”。想要在每一行开始处添加一个星号,你可以编写代码,查找字符串中每个 \n 换行符,然后在它后面添加一个星号。但更容易的做法是,使用 split() 方法得到一个字符串的列表,其中每个表项就是原来字符串中的一行,然后在列表中每个字符串前面添加星号。

让程序看起来像这样:

#! python3
# bulletPointAdder.py - Adds Wikipedia bullet points to the start
# of each line of text on the clipboard.
import pyperclip
text = pyperclip.paste()
# Separate lines and add stars.
lines = text.split('\n')
for i in range(len(lines)): # loop through all indexes in the "lines" list
 lines[i] = '* ' + lines[i] # add star to each string in "lines" list
pyperclip.copy(text)

我们按换行符分隔文本,得到一个列表,其中每个表项是文本中的一行。我们将列表保存在 lines 中,然后遍历 lines 中的每个表项。对于每一行,我们在开始处添加一个星号和一个空格。现在 lines 中的每个字符串都以星号开始。