最初,我打算创建一个包含 25 个或更多单词的行中的单词列表,然后也对其进行迭代。 这是我到目前为止所拥有的:
text = 'text.txt'
handle= open(text)
line_count=0
for line in handle:
line_count = line_count + 1
word_count = 0
split_line = line.split()
for word in split_line:
word_count = word_count + 1
if count == 25:
print(line)
我希望能够创建一个新行,以便文本不会超出屏幕边框。
最佳答案
我们不要重新发明轮子,有一个库可以让你根据长度来换行文本,textwrap
。这是一个例子:
import textwrap
lenght = 200
with open("test.txt", "r") as file: # Open a file with read permissions.
content = file.read() # Read the content of the file
wrapper = textwrap.TextWrapper(width=lenght) # Define the wrapper
wrapped_text = wrapper.wrap(text=content) # Wrap your text, this creates a List
with open("test_result.txt", "w") as file2: # Open a file with write permissions.
file2.write("\n".join(wrapped_text)) # Write the wrapped list into the file.
我使用了两个不同的文件,因为我觉得如果您在处理后可以看到两个文件之间的差异,对您来说会更容易。
奖励:由于我们使用 with
我们不必关闭文件,它们会自动关闭。上下文管理器总是值得学习的东西,看看:https://book.pythontips.com/en/latest/context_managers.html
关于python - 当Python中有25个单词时,如何读取文件并插入新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72064622/