2016-03-29 9 views
-1

私はテキストファイルを持っています。このファイルで特定の単語を検索し、直後の行を返したいと思います。後続の行からファイルを検索するにはどうすればよいですか?

私のテストケースでは、色の名前の前に多くの色数値があります。私は色の名前を入力して数値を取得できるようにしたい。これは私のコードです:

def colorF(c): 
    h = 0 
    r = False 
    try: 
     f = open("Colors.txt") 
     t = list(f.read().split()) 
     for line in t: 
      h += 1 
      if str(c) in line: 
       u = line 
       print(u) 
       go = False 
       start = '(' 
       end = ')' 

       with open("Colors.txt") as infile: 
        for l in infile: 
         g = l.strip() 
         if start in g and str(c) in line: go = True 
         elif end in g: 
          go = False 
          continue 
         if go: return (g) 
    finally: 
     f.close() 

私は助けを得ることができますか?私は何が間違っているのか分かりません。

+1

サンプルファイルを用意してください。ほんの数行なので、私たちは一般的な構造を知っています。 – timgeb

+0

またあなたのコードは私を狂わせます。 – timgeb

答えて

1

です。あなたが与えられた行に色の名前を見つけた場合はまず、一度だけ一度に一つの行をファイルの読み込み、およびだけnext lineを返すことによって簡素化:

def colorF(colorName): 
    with open("Colors.txt") as colorFile: 
     for line in colorFile: 
      if str(colorName) in line: 
       try: 
        return next(colorFile) 
       except StopIteration: 
        raise Exception("File is malformed: no value existed after color found.") # There is probably a more specific iteration that works here 
     return Exception("Color not found") # There is probably a more appropriate exception to return here 

あなたのコードは、他のmishagusの束を持っている:それは不明ですあなたはそれで何をしようとしているのですか?あなたの説明に基づいて、それは不必要なようです。

Exception色が見つからないか、ファイルが色を検出したが後続の値がない場合に発生します。これはいくつかの方法で処理することができますが、この場合は呼び出し側のコードがファイルから値を取得できないことを知るために例外を送出することをお勧めします。

+0

良いお呼び@timgeb私は答えを更新しました。 –

+0

ありがとう! – CollintheWhite

0

私は本当にあなたの状態が何であるかを理解しない...しかし、これはおそらく、あなたはあなたのコードが複雑になり過ぎているように見える答え

for line in f: 
    if some_condition(line): 
     return next(f) # return the next line 
1

あなたはスプリットを使用しているので、ファイルのフォーマットの私の理解では、これです:

Blue 12 
Red 34 
Green 56 

そしてません。このように:それは私が使用する場合なら

Blue 
12 
Red 
34 

を:

def colorF(c): 
with open("Colors.txt", "r") as file: 
    for line in file: 
     words = line.split() 
     for word in words: 
      if word in c: 
       try: 
        ret = next(word) 
        return int(ret) 
       except ColorError: 
        raise Exception("The specified color was not in the file.") 
        return None 
関連する問題