如何应用python脚本将项目符号点添加到记事本中的列表?

2024-09-30 12:17:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个愚蠢的问题,所以当我在网上搜索时,我只找到了更高级问题的答案。在

好吧,我做了一个剧本:bulletPointAdder.py

在记事本上我有一个列表(每行一个项目)。

如何将我制作的脚本应用到记事本文件?

(这个脚本是按预期工作的,因为我使用的是Al-Stweigart的“用Python自动化无聊的东西”——但是这本书没有帮助或者我无法理解)

#! 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
text = '\n'.join(lines)
pyperclip.copy(text)

Tags: oftheto答案textinpy脚本
1条回答
网友
1楼 · 发布于 2024-09-30 12:17:03

在这段代码中,您使用了一个库“pyperclip”,它将把剪贴板中的文本(当您复制ctrl+insert时)放入一个变量“text”。在

然后“text”被拆分成一个行列表,因为“\n”表示行尾。在

然后(缩进错误:'for'行应该与前面的行一样位于缩进处)代码采用i索引的每一行(因为len(lines)是列表'lines'的长度),并在列表'lines'的每个元素i中添加字符串'*'

现在,在循环之外,变量“text”变成了一个字符串,它合并了行“lines”列表中的所有新元素

最后,pyperclip.复制(因此它调用在库“pyperclip”中定义的函数“copy”)将字符串复制到剪贴板。在

import pyperclip    # a librairy of function that allows you communicating with the clipboard
text = pyperclip.paste()  # takes the string from the clipboard

 and add stars.
lines = text.split('\n') # Separate the text into a list of lines
for i in range(len(lines)): # loop through all elements of the list in the "lines" list using the index 'i'
        lines[i] = '* ' + lines[i] # merges a star and a space behind the previous line of text. For each line i of 'lines', add '* '
text = '\n'.join(lines) # merges all elements of the list 'lines' into a string
pyperclip.copy(text) # export the string 'text' to the clipboard

相关问题 更多 >

    热门问题