2011-08-04 7 views
0
import string 

## This part of the code initializes the program by recieving inputs and saving 
## them as strings. 
## It also currently works! 

intext = str.lower(raw_input("Please input the text you are going to use. ")) 
##print intext 
instring = str.lower(raw_input("Please input your string. ")) 
##print instring 
inlengthminus = int(raw_input("Please input the number of words you would like before the matched word. ONLY PUT AN INTEGER HERE!")) 
inlengthplus = int(raw_input("Please input the number of words you would like after the matched word. ONLY PUT AN INTEGER HERE!")) 
## This part of the code splits the text into searchable lists. 
## It only works when the cases match, which is why the search lists 
## convert the text to lowercase. 

searchtext=str.split(intext) 
##print searchtext 
searchstring=list(instring+1) 
##print searchstring 

## This is the actual search process. 
## It works, mostly. 

length = len(searchtext) 
stringlength = len(searchstring) 
##print stringlength 

x=0 
for a in range(0,length): 
    print a 
    print searchstring[x] 
    print x 
    if searchstring[x] in searchtext[a]: 
     if (a-inlengthminus)<0: 
      print "You almost caused an error, please pick a number of words before your matched word that won't call text that doesn't exist." 
      break 
     else: 
      print searchtext[a-inlengthminus:a+inlengthplus+1]  
      x+=1 
    else: 
     pass 

私はこのプログラムがsearchstring [x]の値をsearchstringの長さより長く呼び出すのを止める方法を知りません。 xがこのオーバーフローエラーを起こさないようにする方法はありますか?このプログラムが存在しないリスト要素を呼び出さないようにするにはどうすればよいですか?

+1

'x 'が' searchstring'の長さを通過するときに何をしたいですか? – GaretJax

+0

このコードは何をしていますか?ここでどのような入出力をお探しですか? – Santa

+1

それはメッセージ生成ジェネレータです。このプログラムは、入力テキスト(小説やニュースレポートなど)と入力文字列(John Cageという名前のような)を受け取り、入力文字列内に文字を含むテキスト取得ワードを実行します。私は入力文字列の最後の文字を越えたときにxを0にリセットしたいので、テキストの長さが走査されるまでプログラムが実行され続けます。私の質問を明確にするのを手伝ってくれてありがとう。 – Alex

答えて

1

は、モジュラス演算子が除算を行い、剰余を返し

x = (x + 1) % len(searchstring) 

x+=1 

を交換します。 xが0からsearchstringの長さになるように、モジュラスは何もしません(それ自身を返します)。 x == searchstringの長さの場合、分割時に余りがないため、0にリセットされます。

+0

それでした!完全な初心者を助けてくれてありがとう。 – Alex

+0

@alexあなたは、正規表現と 're'モジュールの使用を検討するべきでしょう。 – Keith

関連する問題