Python限定文本文件中的特定位置进行操作

2024-04-19 10:50:49 发布

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

我有一个文本文件,其中包含如下数据

AA 331             
line1 ...   
line2 ...    
% information here     
AA 332   
line1 ...    
line2 ...    
line3 ...   
%information here    
AA 1021   
line1 ...   
line2 ...  
% information here      
AA 1022    
line1 ...   
% information here     
AA 1023    
line1 ...    
line2 ...    
% information here    

我只想对在第"AA 331"行和第"AA 1021"行之后,而不是第"AA 332""AA 1022"行和第"AA 1023"行之后的最小整数后面的“信息”执行操作。你知道吗

这只是一个大文件的样本数据

下面的代码我试图解析文本文件,并在列表“list1”中获得“AA”之后的整数,在第二个函数中,我将它们分组以获得“list2”中的最小值。这将返回像[3311021,…]这样的整数。所以我想提取“aa331”后面的行并执行操作,但我不知道如何继续。你知道吗

from itertools import groupby
def getlineindex(textfile):
    with open(textfile) as infile:
    list1 = []
    for line in infile :
        if line.startswith("AA"):
            intid = line[3:]
            list1.append(intid)
    return list1

def minimalinteger(list1):
     list2 = []
     for k,v in groupby(list1,key=lambda x: x//10):
           minimalint = min(v)
           list2.append(minimalint)
     return list2

list2包含“AA”后面的最小整数[3311021,…]


Tags: 数据informationheredefline整数infileaa
2条回答

您可以使用以下方法:

import re

matcher = re.compile("AA ([\d]+)")
already_was = []
good_block = False

with open(filename) as f:
   for line in f:
        m = matcher.match(line)
        if m:
           v = int(m.groups(0)) / 10
        else:
           v = None

        if m and v not in already_was:
            good_block = True
            already_was.append(m)
        if m and v in already_was:
            good_block = False
        if not m and good_block:
            do_action()

只有当组中的第一个值是最小值时,这些代码才起作用。你知道吗

好吧,这是我的解决办法。在较高的层次上,我逐行进行,观察AA行以知道何时找到数据块的开始/结束,并观察我所称的运行编号以知道是否应该处理下一个块。然后,我有一个处理任何给定块的子程序,基本上读取所有相关行,并在需要时处理它们。该子例程监视nextAA行,以便知道它何时完成。你知道吗

import re

runIdRegex = re.compile(r'AA (\d+)')

def processFile(fileHandle):
    lastNumber = None  # Last run number, necessary so we know if there's been a gap or if we're in a new block of ten.
    line = fileHandle.next()
    while line is not None:  # None is being used as a special value indicating we've hit the end of the file.
        processData = False
        match = runIdRegex.match(line)
        if match:
            runNumber = int(match.group(1))
            if lastNumber == None:
                # Startup/first iteration
                processData = True
            elif runNumber - lastNumber == 1:
                # Continuation, see if the tenths are the same.
                lastNumberTens = lastNumber / 10
                runNumberTens = runNumber / 10
                if lastNumberTens != runNumberTens:
                    processData = True
            else:
                processData = True

            # Always remember where we were.
            lastNumber = runNumber

            # And grab and process data.
            line = dataBlock(fileHandle, process=processData)
        else:
            try:
                line = fileHandle.next()
            except StopIteration:
                line = None

def dataBlock(fileHandle, process=False):
    runData = []
    try:
        line = fileHandle.next()
        match = runIdRegex.match(line)
        while not match:
            runData.append(line)
            line = fileHandle.next()
            match = runIdRegex.match(line)
    except StopIteration:
        # Hit end of file
        line = None

    if process:
        # Data processing call here
        # processData(runData)
        pass

    # Return line so we don't lose it!
    return line

给你一些笔记。首先,我同意Jimilian的观点,即应该使用正则表达式来匹配AA行。你知道吗

第二,我们讨论的关于何时处理数据的逻辑在processFile中。特别是这些线路:

        processData = False
        match = runIdRegex.match(line)
        if match:
            runNumber = int(match.group(1))
            if lastNumber == None:
                # Startup/first iteration
                processData = True
            elif runNumber - lastNumber == 1:
                # Continuation, see if the tenths are the same.
                lastNumberTens = lastNumber / 10
                runNumberTens = runNumber / 10
                if lastNumberTens != runNumberTens:
                    processData = True
            else:
                processData = True

我假设我们不想处理数据,然后确定何时处理。从逻辑上讲,你可以做相反的事情,假设你想处理数据,然后确定你什么时候不想处理。接下来,我们需要存储lastrun的值,以便知道我们是否需要处理这个run的数据。(注意第一次运行的边缘情况)我们知道,当序列中断(两次运行之间的差值大于1)时,我们希望处理数据,这是由else语句处理的。我们还知道,当序列以十位数递增时,我们需要处理数据,这是由整数除以10来处理的。你知道吗

第三,注意数据块返回的数据。如果不这样做,就会丢失导致dataBlock停止迭代的AA行,processFile需要这一行来知道是否应该处理下一个数据块。你知道吗

最后,我选择了文件句柄.next()和异常处理,以确定何时到达文件末尾。但别以为这是唯一的办法。:)

如果您有任何问题,请在评论中告诉我。你知道吗

相关问题 更多 >