我有此案文,我将从中分享一部分,
ROMEO
但是,柔软!窗外有什么光线打破?它是东方,朱丽叶是太阳。
JULIET
Ay me!
ROMEO
她说:哦,再说一次,聪明的天使!为你的艺术。
JULIET
罗密欧,罗密欧!为何你偏偏是罗密欧?否认你的父亲,拒绝你的名字;
ROMEO
我应该听到更多,还是我要在这说话?。
我想编写一个循环,在该行中查找名称并将其后的内容保存到特定文件中,在这种情况下,如果找到的单词是“ ROMEO”,则将其保存到“ Romeo.txt ”,直到找到单词“ JULIET”,然后将所有内容保存到“ Juliet.txt”。我尝试通过合并循环和if语句自己对它进行编码,但这使我无所适从。句柄=打开(“ romeo-full.txt”)船长=“ ROMEO”
handle = open("romeo-full.txt")
skipper = "ROMEO"
for line in handle:
line = line.strip()
while skipper == "ROMEO":
print(line) #This would be the write to file code
if line.startswith("ROMEO"):
skipper = "JULIET"
break
else:
continue
while skipper == "JULIET":
print(line) #This would be the write to file code
if line.startswith("ROMEO"):
skipper = "ROMEO"
break
else:
continue
输出基本上是“ ROMEO”行循环,我知道它永远来自循环通过第一行的while循环,但是我找不到比这更接近我想要的方法。
避免重复代码的一种方法是将主文件中的标头用作写入哪个文件的“选择器”。类似于:
with open("romeo-full.txt") as handle, \
open("romeo.txt", 'w') as r_f, \
open("juliet.txt", 'w') as j_f:
file_chooser = {"ROMEO": r_f,
"JULIET": j_f}
for line in handle:
try:
cur_file = file_chooser[line.strip()]
except KeyError:
cur_file.write(line)
try/except
块的目的是仅在遇到一个标题(然后跳过它)时才更改cur_file
。
避免这种情况的一种方法是将dict的get
方法与默认设置为get
一起使用(因此它仅在标头上更改:]
cur_file
这里的缺点是每次也将标头写入文件。
您可以像这样写入多个文件:
with open("romeo-full.txt") as handle, \
open("romeo.txt", 'w') as r_f, \
open("juliet.txt", 'w') as j_f:
file_chooser = {"ROMEO": r_f,
"JULIET": j_f}
cur_file = r_f
for line in handle:
cur_file = file_chooser.get(line.strip(), cur_file)
cur_file.write(line)
您应始终使用with open('example1.txt', 'w') as file_1 \
, open('example2.txt', 'w') as file_2 \
, open('example3.txt', 'w') as file_3 \
, open("romeo-full.txt", 'r') as handle:
for line in handle:
if condition_1:
file_1.write(line)
elif condition_2:
file_2.write(line)
elif condition_3:
file_3.write(line)
而不是with
和open
的原因是,如果由于某种原因您没有关闭(例如程序崩溃或忘记添加它),则文件不会关闭,占用空间。我已经看到经常打开且未关闭的文件导致服务器崩溃!