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

时间:2018-11-12 19:11:36

标签: python python-3.x

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


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 

2 个答案:

答案 0 :(得分:5)

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

main :: String -> IO ()
main query = uninterruptibleMask $ \restore -> do
  results <- newIORef []
  xe      <- try $ restore $ search query results
  case xe of
    Right x -> printCompleted >> printResults x
    Left  e -> do
      printInterrupted
      readIORef results >>= printResults
      case e of
        UserInterrupt -> return ()
        _             -> throw e

答案 1 :(得分: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')