gpt4 book ai didi

python - 删除括号内包含的文本

转载 作者:行者123 更新时间:2023-11-30 23:31:37 24 4
gpt4 key购买 nike

我正在尝试编写一个清理文本文件的程序;具体来说,我正在尝试清理莎士比亚的《仲夏夜之梦》的副本。我正在尝试编写一个代码来消除脚本中的舞台方向,以便此文本:

THESEUS Go, bid the huntsmen wake them with their horns.

[Horns, and shout within. DEMETRIUS, LYSANDER,HERMIA, and HELENA awake

and start up.]

Good-morrow, friends. Saint Valentine is past; Begin these wood-birds but to couple now?

LYSANDER Pardon, my lord.

[He and the rest kneel to THESEUS.]

THESEUS

I pray you all, stand up. I know you two are rival enemies; How comes this gentle concord in the world, That hatred is so far from jealousy To sleep by hate, and fear no enmity?

变成这样的文字:

THESEUS Go, bid the huntsmen wake them with their horns.

Good-morrow, friends. Saint Valentine is past; Begin these wood-birds but to couple now?

LYSANDER Pardon, my lord.

THESEUS

I pray you all, stand up. I know you two are rival enemies; How comes this gentle concord in the world, That hatred is so far from jealousy To sleep by hate, and fear no enmity?

这是我编写的代码,但它在我假设的 while 循环上被挂起。任何帮助将不胜感激!

def cleanDirections(inFilename, outFilename):
inFile = open(inFilename, "r")
outFile = open(outFilename, "w")

line = inFile.readline()

while line != "":

if line.startswith("[") == True:
if line.endswith("]") == True:
line = inFile.readline()
else:
while line.endswith("]") == False:
line = inFile.readline()
line = inFile.readline()

else:
outFile.write(line)
line = inFile.readline()

另外:如果可以用这种语法提供帮助,那就太好了。我还在学习中,所以我还不知道更高级的Python。

最佳答案

由于您的括号跨越多行,因此您无法逐行执行此操作。使用:

text = inFile.readLines()
text = re.sub("\[[^\]]*\]","",text) #will kill any [STUFF]

关于python - 删除括号内包含的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com