0

次の方法で処理する膨大な数の文字列があります。文字列ごとに、位置 9 を除いて、位置 3 から 15 までの文字を抽出する必要があります。

したがって、入力 "F01MBBSGB50AGFX0000000000" の場合、出力は "MBBSGB50AGFX" になります。

明らかな方法はs[3:11] + s[12:15].
しかし、処理する必要のある膨大な量のデータを考えると、これを行うための推奨される方法について助けが必要です。

4

1 に答える 1

1

抽出する文字列の位置が固定されているこのようなものがある場合、Python スライスを使用して、抽出する対象フィールドを事前に定義するのが好きです。これは少しやり過ぎかもしれませんが、すべてのフィールドの位置と長さのカウント情報を単一の管理しやすいデータ構造に保持[2:10][12:15]ます。

#         1         2
#123456789012345678901234
samples = """\
F01MBBSGB50AGFX0000000000
F01MBCSGB60AGFX0000000000
F01MBDSGB70AGFX0000000000""".splitlines()

# define the different slices you want to get from each line;
# can be arbitrarily many, can extend beyond the length of the
# input lines, can include 'None' to imply 0 as a start or 
# end-of-string as the end
indexes = [(3,9),(10,15)]

# convert to Python slices using 'slice' builtin
slices = [slice(*idx) for idx in indexes]

# make a marker to show slices that will be pulled out
# (assumes slices don't overlap, and no Nones)
marker = ''
off = 0
for idx in sorted(indexes):
    marker += ' '*(idx[0]-off) + '^'*(idx[1]-idx[0])
    off = idx[1]

# extract and concat
for s in samples:
    print s
    print marker
    print ''.join(s[slc] for slc in slices)
    print

版画:

F01MBBSGB50AGFX0000000000
   ^^^^^^ ^^^^^
MBBSGB0AGFX

F01MBCSGB60AGFX0000000000
   ^^^^^^ ^^^^^
MBCSGB0AGFX

F01MBDSGB70AGFX0000000000
   ^^^^^^ ^^^^^
MBDSGB0AGFX

(start,length)必要に応じて、次のように、タプルを使用して抽出する部分を定義することもできます。

fields = [(3,6), (10,5)]

次に、これらを次のようにスライスに変換します。

slices = [slice(start,start+length) for start,length in fields]

上記の残りのコードはすべて同じままです。

于 2013-05-04T07:27:15.090 に答える