使用Python从文本文件中删除x行段落

时间:2011-03-04 00:30:45

标签: python

我有一个长文本文件,每个段落有6行和7行。我需要将所有七行段落写入文件,并将六行段落写入文件。 或删除6行(7行)段落。 每个段落用空行(或两个空行)分隔。 文本文件示例:

Firs Name Last Name
address1
Address2
Note 1
Note 2
Note3
Note 4

First Name LastName
add 1
add 2
Note2
Note3
Note4

etc...

我想在Windows上使用python 3。欢迎任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

作为对stackoverflow的欢迎,并且因为我认为您现在已经搜索了更多代码,我建议您使用以下代码。

它验证段落不超过7行且不少于6行。它会在源中存在此类段落时发出警告。

您将删除所有打印件以获得干净的代码,但使用它们可以遵循算法。

我认为它没有任何错误,但不要把它当作100%确定。

这不是唯一可行的方式,但我选择了可​​以用于所有类型文件的方式,无论大与否:一次迭代一行。可以一次读取整个文件,然后分成行列表,或者在正则表达式的帮助下处理;但是,当文件很大时,一次读取所有内容都会耗费内存。

with open('source.txt') as fsource,\
     open('SIX.txt','w') as six,  open('SEVEN.txt','w') as seven:

    buf = []
    cnt = 0
    exceeding7paragraphs = 0
    tinyparagraphs = 0

    line = 'go'
    while line:
        line = fsource.readline()
        cnt += 1
        buf.append(line)

        if len(buf)<6 and line.rstrip('\n\r')=='':
            tinyparagraphs += 1
            print cnt,repr(line),"this line of paragraph < 6 is void,"+\
                  "\nthe treatment of all this paragraph is skipped\n"+\
                  '\n# '+str(cnt)+' '+ repr(line)+" skipped line "
            buf = []
            while line and line.rstrip('\n\r')=='':
                line = fsource.readline()
                cnt += 1
                if line=='':
                    print "line",cnt,"is '' , EOF -> the program will be stopped"
                elif line.rstrip('\n\r')=='':
                    print '#',cnt,repr(line)
                else:
                    buf.append(line)
                    print '!',cnt,repr(line),' put in void buf'
        else:
            print cnt,repr(line),' put in buf'




        if len(buf)==6:
            line = fsource.readline() # reading a potential seventh line of a paragraph
            cnt += 1

            if line.rstrip('\n\r'): # means the content of the seventh line isn't void
                buf.append(line)
                print cnt,repr(line),'seventh line put in buf'
                line = fsource.readline()
                cnt += 1

                if line.rstrip('\n\r'): # means the content of the eighth line isn't void
                    exceeding7paragraphs += 1
                    print cnt,repr(line),"the eight line isn't void,"+\
                          "\nthe treatment of all this paragraph is skipped"+\
                          "\neighth line skipped"
                    buf = []
                    while line and line.rstrip('\n\r'):
                        line = fsource.readline()
                        cnt += 1
                        if line=='':
                            print "line",cnt,"is '' , EOF -> the program will be stopped"
                        elif line.rstrip('\n\r')=='':
                            print '\n#',cnt,repr(line)
                        else:
                            print str(cnt) + ' ' + repr(line)+' skipped line'

                else:
                    if line=='':
                        print cnt,"line is '' , EOF -> the program will be stopped\n"
                    else: # line.rstrip('\n\r') is ''
                        print cnt,'eighth line is void',repr(line)
                    seven.write(''.join(buf) + '\n')
                    print buf,'\n',len(buf),'lines recorded in file SEVEN\n'
                    buf = []

            else:
                print cnt,repr(line),'seventh line: void'
                six.write(''.join(buf) + '\n')
                print buf,'\n',len(buf),'lines recorded in file SIX'
                buf = []
                if line=='':
                    print "line",cnt,"is '' , EOF -> the program will be stopped"
                else:
                    print '\nthe line is',cnt, repr(line)

            while line and line.rstrip('\n\r')=='':
                line = fsource.readline()
                cnt += 1
                if line=='':
                    print "line",cnt,"is '' , EOF -> the program will be stopped"
                elif line.rstrip('\n\r')=='':
                    print '#',cnt,repr(line)
                else: # line.rstrip('\n\r') != ''
                    buf.append(line)
                    print '!',cnt,repr(line),' put in void buf'

if exceeding7paragraphs>0:
    print '\nWARNING :'+\
          '\nThere are '+str(exceeding7paragraphs)+' paragraphs whose number of lines exceeds 7.'

if tinyparagraphs>0:
    print '\nWARNING :'+\
          '\nThere are '+str(tinyparagraphs)+' paragraphs whose number of lines is less than 6.'


print '\n===================================================================='
print 'File SIX\n'
with open('SIX.txt') as six:
    print six.read()


print '===================================================================='
print 'File SEVEN\n'
with open('SEVEN.txt') as seven:
    print seven.read()

我也提出了你的问题,因为这是一个不容易解决的问题,并且不会让你有一个帖子和一个downvote,它是一个开端的士气低落。正如其他人所说的那样,下次尝试让你的演示更好。

编辑:

这是一个简化的代码,用于仅包含6或7行的段落,正好用1或2行分隔,如问题的措辞中所述

with open('source2.txt') as fsource,\
     open('SIX.txt','w') as six,  open('SEVEN.txt','w') as seven:

    buf = []

    line = fsource.readline()
    while not line: # to go to the first non empty line
        line = fsource.readline()


    while True:
        buf.append(line) # this line is the first of a paragraph
        print '\n- first line of a paragraph',repr(line)

        for i in xrange(5):
            buf.append(fsource.readline())
        # at this point , 6 lines of a paragraph have been read
        print '-- buf 6 : ',buf

        line = fsource.readline()
        print '--- line seventh',repr(line),id(line)

        if line.rstrip('\r\n'):
            buf.append(line)
            seven.write(''.join(buf) + '\n')
            buf = []
            line = fsource.readline()
        else:
            six.write(''.join(buf) + '\n')
            buf = []
        # at this point, line is the empty line after a paragraph or EOF
        print '---- line after',repr(line),id(line)

        line = fsource.readline()
        print '----- second line after',repr(line)
        # at this point, line is an empty line after a paragraph or EOF
        # or the first line of a new paragraph

        if not line: # it is EOF
            break
        if not line.rstrip('\r\n'): # it is a second empty line
            line = fsource.readline()
        # now line is the first of a new paragraph


print '\n===================================================================='
print 'File SIX\n'
with open('SIX.txt') as six:
    print six.read()


print '===================================================================='
print 'File SEVEN\n'
with open('SEVEN.txt') as seven:
    print seven.read()