仅打印行中特定单词下方的字符

时间:2012-03-07 22:16:56

标签: python string

我正在尝试编写一个执行两个不同内容的脚本:它选择一个随机单词并使其“跳出”一行,并且它也“转向”一个单词。反过来,我的意思是它选择一个随机的单词,然后只从它下面的那个单词打印相同数量的字符,而不是其他,如下:

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 

上面的代码运行,但只能成功地使文本“跳转”。任何人都可以帮助创建这一列的单词吗?

再次,您可以给予的任何帮助将非常感激。谢谢!

1 个答案:

答案 0 :(得分: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