0

私のコードについて助けが必要です。以下は私の現在の問題です:

  1. numref以下に例を示します。
  2. if-ステートメントを正しく構築しているかどうかはわかりません。

コード:

import subprocess

def p4 (base_num):

    numrefs = ['nums/89/202089/4', 'nums/39/205739/2', 'nums/94/195594/6']
    num_ignore = [150362, 147117, 147441, 143446, 200914]
    ''''
    num_ids.txt
    202089
    205739
    195594
    202090
    202092
    202091
    202084
    202088
    202086
    202076
    202083
    206057
    206056
    '''

    with open('./num_ids.txt', 'rb') as f:
    # Iterate over the file itself
        for line in f:
            num = int(line)
            if num > base_num and num not in num_ignore and line in numrefs:
                #get the match when line matches numrefs
                #if line is 20289,it should match the value nums/89/202089/ in  num_refs and print it here,how can I do it?
                print "OVER"

def main():
    base_num=203456
    p4(base_num)

if __name__ == '__main__':
    main()
4

1 に答える 1

1

質問を正しく理解している場合、コードは次の 2 つの理由で失敗しています。

  1. で識別される文字列は でline終わります: これは、 内を検索する前\nに ping する必要があります。stripnumrefs
  2. line in numrefsnumrefsの文字列が長いため、常に失敗します。これらの文字列内を検索したいようです。

p4()これら 2 つの問題に対処する のバージョンを次に示します。

def p4(base_num):
    numrefs = ['nums/89/202089/4', 'nums/39/205739/2', 'nums/94/195594/6']
    num_ignore = [150362, 147117, 147441, 143446, 200914]

    with open('./num_ids.txt', 'rb') as f:
        for line in f:
            text = line.strip()  # Trim trailing whitespace and newline
            num = int(text)
            if (num > base_num
                    and num not in num_ignore
                    # Check for any substring in list of strings
                    and any(text in numref for numref in numrefs)):
                print text

numref見つかった文字列を出力する必要がある場合(存在する場合)、 if-statement を次のように変更します。

            if num > base_num and num not in num_ignore:
                result = [numref for numref in numrefs if text in numref]
                if result:
                    print result[0]

このifステートメントは、独自のテスト可能なメソッドに抽出する必要があります。

于 2012-12-31T09:24:38.250 に答える