使用头拆分文本文件

2024-05-14 04:19:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个输入文本文件,我正在读取并存储在列表中的所有内容。之后,我将根据列表中出现的特定文本拆分列表。在

这是函数。在

import re
def readFile1(file1):
    f = file1.read().split('\n')
    #print f
    ctrlList1 = []
    mfcList1 = []

    for str in f:
        if re.search("MegaMon> mfc",str):
            print "splitting\n"
            break
        else:
            ctrlList1.append(str)

    print ctrlList1, "\n\n\n"

这样可以很好地保存ctrlList1,直到文本megamon> mfc出现在主列表中。但是我想把MegaMon> mfc之后的行保存在mfcList1中。我不能那样做。在

我试过了:

^{pr2}$

但这似乎行不通。我需要将文本文件保存在两个不同的列表中。任何帮助都将不胜感激。在


Tags: 函数文本importre内容列表deffile1
3条回答

怎么样

 import re
 mfcList1, ctrlList1 = [],[]
 # read the whole file as a list of lines - its easier
 with open(file1, 'r') as f1:
     lines = f1.readlines()

 # for each line, search for your string. 
 # If you have found MegaMon append one mfcList1, else append ctrlList1
 foundMegaMon = False
 for line in lines:
     if re.search("MegaMon> mfc",line):
          foundMegaMon = True
     if foundMegaMon:
          mfcList1.append(line)
     else:
          ctrlList1.append(line)

怎么样:

 for index, str in enumerate(f):
        if re.search("MegaMon> mfc",str):
            print "splitting\n"
            mfcList1=f[ index + 1 : ]
            break
        else:
            ctrlList1.append(str)

您可能需要更改[index+1:]中的索引(从我的脑子里写出来),但一般来说应该可以。在

基本上,这使用enumerate来获取“for”循环中当前元素的索引,当达到拆分点时,将“f”列表的其余部分分配给“mfcList1”列表。在

其他解决方案似乎也不错。这个看起来更优雅一点:

ctrlList1=[]
mfcList1=[]
curlist = ctrlList1                   # Initially, append to ctrlList1
for line in file1:
    str = line.rstrip("\n")           # Remove trailing newlines

    if re.search("MegaMon> mfc",str):
        print "splitting\n"
        curlist = mfcList1            # From now on, append to mfcList1
        continue
    curlist.append(str)

print ctrlList1, "\n\n\n"
print mfclList1, "\n\n\n"

相关问题 更多 >