2012-03-07 72 views
0

我正在嘗試編寫一個執行兩個不同操作的腳本:它選取一個隨機單詞並使其「跳出」一行,並且「 「一句話。通過反過來,我的意思是它選擇一個隨機單詞,然後只打印相同的字符數,從這個詞它下面,沒有別的,像這樣:僅打印一行中特定單詞下的字符

this is a thing that I am typing 
      sdfas 
      wertq 
      wsvsd 
      swefs 

這就是我的意思是通過使「跳」出列:

  thing 
this is a  that I am typing 

我的問題是,我無法弄清楚如何說「打印在X字符[X]號」

這裏是我的代碼,如下:

import random 
import sys 

s = open('sonnets.txt') 

counting = 0 

for line in s: 
    line.strip() 
    randomInt = random.randint(1,100) 
    counting = counting+1 
    words = line.split() 
    test = 1 
    if (randomInt < 2*counting): 
     if (len(words) > 0): 
      r = random.choice(words) 
      if r in line: 
       ind = line.index(r) 
       wordChoice = len(r) 
       print ((" " * (ind))+r).upper() 
       whiteSpace = wordChoice+2 
       newLine = line.replace(r, (" " * whiteSpace)) 
       print newLine 
      turn = random.choice(words) 
      if turn in line: 
       turnCheck = True 
       ind = line.index(turn) 
       wordChoice = len(turn) 
       print ((" " * (ind))+turn) 
       foo = line[ind:ind+4] 
       print ((" " * (ind))+foo) 
    else: 
     print line 

上面的代碼運行,但只能使文本「跳轉」成功。任何人都可以幫助創建這一列的話?

再次,任何幫助,你可以給予非常感謝。謝謝!

+0

那豈不是在兩種情況下更容易只是爲了找到索引要執行的單詞的第一個字符的char數組採取行動?然後,你可以簡單地打印一個新的行「」索引和​​打印隨機字符 – Jkh2 2012-03-07 22:22:49

+1

這個問題會更好http://codereview.stackexchange.com/ – 2012-03-07 22:23:14

+0

@StevenRumbalski我不知道存在,謝謝!我會在那裏發佈它。 – spikem 2012-03-07 22:33:16

回答

0
txt='this is a thing that I am typing' 

jumpword='thing' 
jumpind=txt.find(jumpword) 
newtxt=str(txt) 
if jumpind>=0: 
    newtxt=newtxt.replace(jumpword," "*len(jumpword),1) 
    newtxt=" "*jumpind+jumpword+'\n'+newtxt 
print newtxt 

結果:

  thing 
this is a  that I am typing 

字轉折點:

import random 
def randword(length,sourcelist): 
    # get random word: (move this out of the function if you need to keep it the same) 
    rword=random.sample(sourcelist,1)[0] 
    # get length number of letters from it. 
    return "".join(map(lambda dummy:random.sample(rword,1)[0],range(length))) 

print txt 
# make 5 turns: 
for i in range(5): 
    print " "*jumpind+randword(len(jumpword),txt.split()) 

結果:

this is a thing that I am typing 
      IIIII 
      aaaaa 
      IIIII 
      yngtt 
      hthti 
相關問題