2011-08-04 21 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

這是一個mesostic生成器。該程序將輸入文本(如小說或新聞報道)和輸入字符串(如John Cage的名稱),然後在輸入字符串中依次遍歷包含字母的文字抓取單詞。我想在x越過輸入字符串中的最後一個字母時將x重置爲0,以便程序繼續運行,直到遍歷文本的長度。謝謝你幫我澄清我的問題。 – Alex

回答

1

替換

x+=1 

隨着

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

模數運算符做除法,並返回餘數。所以x從0到searchstring的長度,模數什麼都不做(返回自己)。如果x ==搜索字符串的長度,它將「重置」爲0,因爲分割時沒有餘數。

+0

這樣做!感謝您幫助完成新手。 – Alex

+0

@alex你應該考慮使用正則表達式和're'模塊。 – Keith