删除括号内的文本

时间:2013-11-06 02:01:55

标签: python file python-3.x while-loop readline

我正在尝试编写一个清理文本文件的程序;具体来说,我正在试图清理一部莎士比亚的“仲夏夜之梦”。我正在尝试编写一个代码来消除脚本中的阶段方向,以便这个文本:

  

THESEUS去吧,让猎人用他们的角唤醒他们。

     

[喇叭,并在内心大喊。 DEMETRIUS,LYSANDER,HERMIA和HELENA醒着

     

然后启动。]

     明天晚上,朋友们。圣瓦伦丁过去了;开始这些木鸟   但现在要结合吗?

     

LYSANDER Pardon,我的主人。

     

[他和其他人跪在THESEUS。]

     

THESEUS

     

我祈祷你们,站起来。我知道你们两个是对手的敌人;世界上这种温和的和谐怎么样,那种仇恨就是如此   远离嫉妒因仇恨而入睡,不怕敌意?

成为这样的文字:

  

THESEUS去吧,让猎人用他们的角唤醒他们。

     明天晚上,朋友们。圣瓦伦丁过去了;开始这些木鸟   但现在要结合吗?

     

LYSANDER Pardon,我的主人。

     

THESEUS

     

我祈祷你们,站起来。我知道你们两个是对手的敌人;世界上这种温和的和谐怎么样,那种仇恨就是如此   远离嫉妒因仇恨而入睡,不怕敌意?

这是我编写的代码,但它正在挂起,在我假设的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。

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

这是一个非常简单的方法,做了很多假设,比如:

  1. 只有第一栏中的“[”才有意义。
  2. “[”和“]”不嵌套 - 只有一级方括号。
  3. 在“]”之后的一行(除了空格之外)没有任何内容。 “]之后的任何内容都将丢失。
  4. 如果你能和那些人一起生活:

    inFile = open(inFilename, "r")
    outFile = open(outFilename, "w")
    skipping = False
    for line in infile:
        if skipping:
            # don't print this line no matter what,
            # hut stop skipping if "]" in line
            if "]" in line:
                skipping = False
        elif line.startswith("["):
            # don't print this line either no matter what,
            # and start skipping if "]" _not_ in the line
            skipping = "]" not in line
        else:
            outfile.write(line)
    infile.close()
    outfile.close()
    if skipping:
        raise ValueError("hit end of file with unclosed '['!")
    

    如果你不能忍受这些限制,那就会变得更复杂; - )

答案 2 :(得分:0)

不使用re

while "[" in string:
    string=string.replace(string[string.find("["):string.find("]")+1],"")

您必须将所有文件都读到string才能执行此操作。

答案 3 :(得分:0)

我是python的新手,不过我是用C-Like方式做的。这很容易理解:)

newFile = open('out.txt', 'w')

inStageDirections = False

with open('sp.txt') as f:
    for c in f.read():
        if inStageDirections is False and c == '[':
            inStageDirections = True
        elif inStageDirections is True and c == ']':
            inStageDirections = False
            continue

        if not inStageDirections:
            newFile.write(c)

        if inStageDirections:
            pass

它通过char解析文件char,并在您计数inStageDirections时设置[,以确保不会在新文件中写入以下文本。虽然我强烈建议你使用正则表达式完成这项工作,因为它更快更优雅。

相关问题