如何使用python [duplicate]限制文本文件中每行的长度

问题描述 投票:-2回答:2

这个问题在这里已有答案:

我有一个以下类型的文本文件 -

eng Firstly, in the course of the last few decades the national eng Secondly, the national courts will be empowered to implement eng However, I am convinced of the fact that the White Paper has put us on the right path.

我想限制每行的长度(比方说)9个单词。我尝试使用python的read_line方法,但它只指定了行的大小。我无法找到任何其他合适的方法。怎么做 ?

样品输出 -

eng Firstly, in the course of the last few
eng Secondly, the national courts will be empowered to
eng However, I am convinced of the fact that 
python python-3.x
2个回答
5
投票

要将字符串的前n个单词作为字符串:

def first_n_words(s, n):
    return ' '.join(s.split()[:n])

1
投票

您可以像这样列出每个单词:

with open(file, 'r') as f:
    lines = []
    for line in f:
        lines.append(line.rstrip('\n').split())

现在使用自动截断的切片将每一行限制为9:

with open(file, 'w') as f:
    for line in lines:
        f.write(' '.join(line[:9]))
        f.write('\n')
© www.soinside.com 2019 - 2024. All rights reserved.