如何编写一个说明step_size为0的滑动窗口算法?

时间:2015-12-13 01:18:30

标签: python algorithm text range sliding-window

我正在处理一个大文本文件,其中包含具有此格式的pi的小数位。请注意,标题是所有数字,并且没有字符串。

标题格式:Number_of_sequences Total_Pi_Digits File_Version_Number

550 10000 5

*Pi Sequence Part 1
1415926535897932384
*Pi Sequence Part 2
6264338327950288419
*Pi Sequence Part 3
1693993751058209749

我需要创建一个滑动窗口,使用三个参数(window_size,step_size和last_windowstart)来裁剪文件。 last_windowstart是最后一个窗口的开始位置。

通过将Total_Pi_Digits除以窗口来确定文件数。

如果文件有99个Total_Pi_Digits,window_size为10,step_size为零,那么总共有11个窗口,因为99 // 10 = 10和99%10在窗口11中留下9个。

对于这个例子,

lastwindow_start应该是90。我不确定我是否需要last_window开始。

对于每个窗口,将创建一个名为PiSubsection的文件# 其中#是窗口编号。

对于每个文件,每个窗口应该具有相同的新标头,其中Number_of_sequences Total_Pi_Digits File_Version_Number是标头格式。

Number_of_sequences Total_Pi_Digits将根据window_size和step_size进行更改,但File_Version_Number不得更改。

我的问题是我的滑动窗口算法没有考虑step_size为0并且它不会产生适量的文件。 到目前为止,它产生的文件数量是原来的两倍。我不确定原因。

此外,即使我理解滑动窗口算法中窗口数量的数学,我也不确定。

如何修复我的滑动窗口算法以接受step_size为0并生成适量的输出文件?

    inputFileName = example.txt

    import shlex

    def sliding_window(windows_size, step_size, lastwindow_start):
        for i in xrange(0, lastwindow_start, step_size):
            yield (i, i + windows_size)

    def PiCrop(windows_size, step_size):

    with open(inputFileName, 'r') as input:
        first_line = shlex.split(input.readline().strip())
        PiNumber = int(first_line[1])

        lastwindow_start = PiNumber-(PiNumber%windows_size)
        flags = [False for i in range(lastwindow_start)]

        first_line[1] = str(windows_size * int(first_line[0]))

        first_line = " ".join(first_line)

        for line in input:
            if line.startswith(first_line[0]):
                pass
            elif line.startswith('*'):
                Indiv = line
            else:
                for counter, window in        enumerate(sliding_window(windows_size,step_size,lastwindow_start)):
                    newline = line[window[0]:window[1]]

                    with open('PiSection{}.txt'.format(counter), 'a') as output:
                        if (flags[counter] == False):
                            flags[counter] = True
                            output.write(first_line + '\n')
                        output.write(Indiv)
                        output.write(newline + '\n')

2 个答案:

答案 0 :(得分:0)

下面的示例代码提供了另一种方法,可以避免需要进行计算。我认为你加载数字文件或者之后实际写'窗口'文件都没有问题,所以我的代码假定它们被加载并生成一个数字窗口数组,可以写入。

从该结果中,您可以简单地遍历现在派生的窗口并像以前一样输出文件,或者您可以深入嵌套数据并根据需要获取单个窗口进行处理。

示例输出如下。如果有任何需要更多细节,请告诉我......

import pprint

# Separated just for easy comparison with the output.
pi_digits = '1415926535' + '8979323846' + '2643383279' + '5028841916' + '9399375105' + '8209749'
total_digits = len(pi_digits)

def splitIntoWindows(digits, window_size):
    result = []
    count = 0
    window = -1
    for digit in digits:
        index = count % window_size
        if index == 0:
            window += 1
            result.append([])
        result[window] += digit
        count += 1
    return result

windows = splitIntoWindows(pi_digits, 10)

print("Split into {} window(s):".format(len(windows)))
pprint.pprint(windows)

示例输出:

Split into 6 window(s):
[['1', '4', '1', '5', '9', '2', '6', '5', '3', '5'],
 ['8', '9', '7', '9', '3', '2', '3', '8', '4', '6'],
 ['2', '6', '4', '3', '3', '8', '3', '2', '7', '9'],
 ['5', '0', '2', '8', '8', '4', '1', '9', '1', '6'],
 ['9', '3', '9', '9', '3', '7', '5', '1', '0', '5'],
 ['8', '2', '0', '9', '7', '4', '9']]

修改

为了避免我的过多假设,这里有一个解析加载的数字文件的片段:

# Assumed these are the contents loaded in:
file_contents = '''
550 10000 5

*Pi Sequence Part 1
1415926535897932384
*Pi Sequence Part 2
6264338327950288419
*Pi Sequence Part 3
1693993751058209749
'''

pi_digits = ''
line_num = 0
for line in file_contents.split('\n'):
    line = line.strip()
    if (len(line) > 0) & (line[0:1] != "*"):
        line_num += 1
        if (line_num > 1):
            pi_digits += line

这应该让pi_digits可以使用了,所以你可以用上面的代码替换上面代码中pi_digits的声明。

答案 1 :(得分:0)

解决方案是将文件存储在列表中,然后使用该列表的块与滑动窗口生成器一起创建所有迷你文件。

inputFileName = "sample.txt"

import itertools
import linecache

def sliding_window(window_size, step_size, lastwindow_start):
    for i in xrange(0, lastwindow_start, step_size):
        yield (i, i + window_size)
    yield (lastwindow_start, total_pi_digits)

def PiCrop(window_size, step_size):

    f = open(inputFileName, 'r')

    first_line = f.readline().split()

    total_pi_digits = int(first_line[0])

    lastwindow_start = total_pi_digits-(total_pi_digits%window_size)

    lastcounter = (total_pi_digits//window_size)*(window_size/step_size)

    flags = [False for i in range(lastcounter)]

    first_line[0] = str(window_size)
    second_line = f.readline().split()
    offset = int(round(float(second_line[0].strip('\n'))))
    first_line = " ".join(first_line)

    f. close()

    with open(inputFileName, 'r') as f:
        header = f.readline()
        data = [line.strip().split(',') for line in f.readlines()]

        for counter, window in enumerate(sliding_window(window_size,step_size,lastwindow_start)):
            chunk = data[window[0]:window[1]]

            print window

            with open('PiCrop_{}.txt'.format(counter), 'w') as output:

                if (flags[counter] == False):
                    flags[counter] = True

                    headerline = float(linecache.getline(inputFileName, window[1]+1)) - offset
                    output.write(str(window_size) + " " + str("{0:.4f}".format(headerline)) + " " + 'L' + '\n')

                for item in chunk:
                    newline = str("{0:.4f}".format(float(str(item).translate(None, "[]'"))-offset))
                    output.write(str(newline) + '\n')