【发布时间】:2016-10-29 15:45:43
【问题描述】:
我正在为学校做作业。这是我第一次尝试使用 Python。我们应该将 Juliet 和 Romeo 复制到一个新文件中,但只有行为和场景指示,只保留 Juliet 和 Romeo 分区。这是我的两个问题:出于某种原因,有时它会复制场景的标题两次。第二个问题,每当J或R说话时,分区必须缩小到一行。似乎无法找到解决问题的方法。 任何帮助将不胜感激。
my clean version, duplicity of indication
# opening files
orig = open('RomeoAndJuliet_clean.txt')
nohead = open('RomeoAndJuliet_cleanNoHeader.txt', 'w')
clean = open('theLovers.txt', 'w')
# declaring booleans
doIHaveToCopyTheLine=False
Romeo = False
Juliet = False
act = False
scene = False
# dissecting the play ##################################
orig = open('RomeoAndJuliet_clean.txt')
# creating the loop
for line in orig.readlines():
# conserving the announcement of acts and scenes
if 'ACT ' in line: # added a space so it doesn't copy a part of the header "CONTRACT"
act = True
else:
act = False
if 'Scene' in line:
scene = True
else:
scene = False
# excluding the other characters of the play
if '>>' in line:
if 'Romeo' in line:
Romeo = True
else:
Romeo = False
if 'Juliet' in line:
Juliet = True
else:
Juliet = False
# assigning functions to the booleans
if Juliet:
clean.write(line)
if Romeo:
clean.write(line)
if scene:
clean.write(line+'\n')
if act:
clean.write(line+'\n')
nohead.close()
clean.close()
orig.close()
【问题讨论】:
-
顺便说一句,在创建布尔变量时,您可以简化语句,只需编写
scene = 'Scene' in line或Juliet = '>>' in line and 'Juliete' in line。 -
第一次出现重复行是因为当变量 act 和 scene 为 True 时,剩余变量 Juliet 和 Romeo 在之前的迭代中也可以为 True。
-
另外,您不需要调用 readlines() 方法来遍历文件 -
for line in orig: ....就足够了。 -
使用str.replace() 将对话框字符串的换行符替换为空格。
-
我应该在哪里以及如何使用它?
标签: python string python-3.x for-loop