2012-03-07 36 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 
相关问题