只打印lin中特定单词下面的字符

2024-09-27 22:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着写一个脚本,它做两件不同的事情:它选择一个随机的单词并使它“跳出”一行,它也“打开”一个单词。反过来,我的意思是,它会随机选取一个单词,然后只从下面的单词中打印相同数量的字符,而不会像这样:

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

这就是我所说的“跳出”底线的意思:

^{pr2}$

我的问题是我不知道怎么说“打印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 

上面的代码运行,但只成功地使文本“jump”。有人能帮我创建这一栏吗?在

再次感谢您的帮助。谢谢您!在


Tags: inimportleniflinerandom单词turn
1条回答
网友
1楼 · 发布于 2024-09-27 22:23:44
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

结果:

^{pr2}$

世界转折:

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

相关问题 更多 >

    热门问题