python - How would I create a new line in a text document after the nth word?
问题描述
I am working on a project in which I have to list a whole lot of things out in this format
[*] This is the first object
[*] This is the second object
[*] When the object gets too long, I need to move it to the next line
to look like this.
I created a .py
file and a .txt
file. I would input the list objects into the .py
file and it would properly format it into the text file. I tried something like this:
text = input('> ')
with open('list.txt', 'a') as f:
f.write(f'[*] {t}\n')
But I can't seem to move it to the next line. Around the 15th word, is when I want to go to a new line.
How can I achieve this?
解决方案
Print the bullet first. Then split the text into a list of words, and print each one in a loop. Inside the loop, keep track of how many words have been printed on the current line, and of you reach 15, print a newline and reset the count to zero.
with open('list.txt', 'a') as f:
# print the bullet
f.write('[*]')
wordcount = 0
# loop over each word in the text
for word in text.split():
f.write(f' {word}')
wordcount += 1
# if this line has 15 words, start a new line
if wordcount == 15:
f.write('\n ')
wordcount = 0
# finally write a newline
f.write('\n')
推荐阅读
- javascript - 如何通过在redux saga中抛出错误来破坏生成器功能
- javascript - Discord.js V12 如何在消息上添加角色?
- keytool - 服务器 crt 和私钥的 Keytool 命令行
- laravel - 更新到 laravel 8 后 Laravel 护照测试失败
- javascript - 如何从 javascript 将 html 模型传递给控制器
- php - SOAP API:PHP 代码不起作用,但 SOAP UI 起作用
- reactjs - 成功验证后导航到主屏幕不起作用
- ios - Swift Firebase 选择 UITableView 原型单元 - UI 问题
- powershell - 如何循环直到没有 IE 进程正在运行
- javascript - 使用缩小的 script.js 及其源映射 .js.map 来恢复原始源代码