python - 当Python中有25个单词时,如何读取文件并插入新行

标签 python

最初,我打算创建一个包含 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/

相关文章:

python - 使用 Python 将 DOCX 文件转换为文本文件

python - 只从 HTML 文件中获取脚本

python - SQLAlchemy:是否知道模型对象的字段名称和值?

python - Django 1.11 自定义用户模型与组

python - 将文件中的普通数字转换为整数列表

Python:子进程并运行具有多个参数的 bash 脚本

python - 如何获取Python错误中异常的日期和时间

Python 类型检查

python - 使用 elasticsearch-py 进行日志记录

python - SQLAlchemy+ Tornado : How to create a scopefunc for SQLAlchemy's ScopedSession?