0

以下代码从 txt 文件中获取每一行。如果该行是“References\n”,则文件应继续获取行,但附加到另一个字符串,删除后续的 '\n' 实例。我应该如何处理嵌套循环和中断?

for file in os.listdir(txtdir):
    if file <> '.DS_Store':
        linenum = 1
        refindicator = 0
        AppendixCheck = 0
        print 'Opening ' + str(file) + '...'
        for line in open(txtdir + file):
            if AppendixCheck == 0:
                #take title from the first line
                if linenum == 1:
                    title = line.replace(",","")
                    print "Title: " + title
                linenum +=1
                #checking for "references\n" line
                if line == "References\n":
                    refindicator +=1
                #after references are found
                if line =='Appendix\n':
                    AppendixCheck +=1
                if refindicator >0:
                    reflist += getline().replace('\n','')
                #reflist = line.split(',')
        print reflist
4

1 回答 1

0

这是我找到的解决方案:

for file in os.listdir(txtdir):
    if file <> '.DS_Store':
        linenum = 1
        refindicator = 0
        AppendixCheck = 0
        refdump = ''
        title = ''
        print 'Opening ' + str(file) + '...'
        for line in open(txtdir + file):
            #The first blank line marks the end of the title
            if line == '\n':
                linenum +=1
            #Only works until appendix is breached
            if AppendixCheck == 0:
                #take title from the first line
                if linenum == 1:
                    title += line.replace('\n','').replace(',','').replace('  ', '')
                    print "Title: " + title
                #checking for "references\n" line
                if line == "References\n":
                    refindicator +=1
                #after references are found
                if 'Appendix' in line:
                    AppendixCheck +=1
                if refindicator >0:
                    refdump += line.replace('\n','')
        reflist = refdump.split(',')
        print reflist
于 2013-04-14T12:22:55.233 回答