Python将文本拆分为x个字符的块

时间:2014-04-19 02:31:32

标签: python regex text formatting

我使用此代码解析文本文件并将其格式化为将每个句子放在一个新行中:

import re

# open the file to be formatted 
filename=open('inputfile.txt','r')
f=filename.read()
filename.close()

# put every sentence in a new line 
pat = ('(?<!Dr)(?<!Esq)\. +(?=[A-Z])')
lines = re.sub(pat,'.\n',f)
print lines 

# write the formatted text 
# into a new txt file 
filename = open("outputfile.txt", "w")
filename.write(lines)
filename.close()

但基本上我需要在110个字符之后拆分句子。因此,如果一行中的句子长于110,它会将其拆分并添加&#39; ...&#39;最后,然后用&#39; ...&#39;开始新的一行。并遵循分裂句子的其他部分,依此类推。

有任何建议如何做到这一点?我不知何故输了。

3 个答案:

答案 0 :(得分:1)

我不知道“行”的内容,但是,如果这不是每行的列表,则需要拆分列表中的所有行。

在你有一个包含这些字符串(行)的列表之后,你可以验证字符串中有多少个字符,如果超过110,你得到107个第一,并在最后加上'...'。像这样:

for i in xrange(0, len(lines)):
    string_line = lines[i]
    if len(string_line) > 110:
        new_string = "{0}...".format(string_line[:107])
        lines[i] = new_string

地名释义:

如果你这样做:

string = "Hello"
print len(string)

结果将是:5

print string[:3]

结果将是:“Hel”

答案 1 :(得分:1)

# open inputfile/read/auto-close 
with open('inputfile.txt') as f:
    lines = f.readlines() # with block auto closes file after block is executed

output = []

for line in lines:
    if len(line) > 110:
        while True: # until break
            output.append(line[:107] + '...') 
            if len(line[107:]) < 111: # if remainder of line is under 110 chars
                output.append('...' + line[107:])
                break
            line = line[107:] # otherwise loop continues with new line definition
    else:
        output.append(line)

# open outputfile/write/auto-closed
with open('outputfile.txt', 'w') as f:
    for line in output:
        f.write(line)

答案 2 :(得分:1)

你不能在python中插入同一个文件。像这样的东西会做你所描述的。

警告:在替换现有文件之前备份文件。

from shutil import move
import os

insert=" #####blabla#### "
insert_position=110


targetfile="full/path/to/target_file"
tmpfile="/full/path/to/tmp.txt"

output=open(tmpfile,"w")

with open(targetfile,"r") as myfile:
    for line in myfile:
        if len(line) >insert_position:
            line=line[:insert_position+1] + insert + "\n" + line[insert_position+1:] 
            myfile.write

        output.write(line)  

output.close()

move(tmpfile,targetfile)