[英]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.我创建了一个.py
文件和一个.txt
文件。 I would input the list objects into the .py
file and it would properly format it into the text file.我会将列表对象输入到.py
文件中,它会将其正确格式化为文本文件。 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.在第 15 个字左右,是我想换行的时候。
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.在循环内部,跟踪当前行上打印了多少个单词,当达到 15 个时,打印一个换行符并将计数重置为零。
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')
Sounds like you're looking for the built-intextwrap
module:听起来您正在寻找内置的textwrap
模块:
import textwrap
wrapper = textwrap.TextWrapper()
wrapper.width = 70
wrapper.initial_indent = '[*] '
wrapper.subsequent_indent = ' '
items = [
'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.',
]
with open('list.txt', 'a') as f:
for item in items:
f.write(wrapper.fill(item) + '\n')
Which produces:其中产生:
[*] 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.
Or use list comprehensions as an alternative.或者使用列表推导作为替代。 It is fast, short and does not require importing libraries.它快速、简短且不需要导入库。
text = 'When the object gets too long, I need to move it to the next line to look like this or even to the next next line if the object gets really long.'
with open('list.txt', 'a') as f:
words = text.split()
words = [w if (n + 1) % 15 else w + '\n ' for n, w in enumerate(words)]
text = ' '.join(words)
f.write(f'[*] {text}\n')
Will result in:会导致:
[*] When the object gets too long, I need to move it to the next line
to look like this or even to the next next line if the object gets
really long.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.