我需要弄清楚是否在文本文件中出现另一个短语之前找到某个短语/行。如果找到该短语,则将通过;如果该短语不存在,则将在截断上方添加一行。值得注意的是,该短语也可以在文档的后面出现。
该txt格式的示例如下:
woijwoi
woeioasd
woaije
Is this found
owijefoiawjwfioj
This is the cutoff
asoi w
more text lines
Is this found
aoiw
搜索应从短语“这是截止”开始。截止线在哪条线上是未知的。如果在截止日期之前存在“是否已找到”,则通过。如果没有,我想在截止日期的正上方添加短语“添加行”。 到目前为止,我已经尝试过的代码示例,其中所有字符串都已预先定义:
find = 'Is this found'
with open(longStr1) as old_file:
lines = old_file.readlines()
with open(endfile1, "w") as new_file:
for num, line in enumerate(lines):
if "This is the" in line:
base_num = num
for num in range(1, base_num):
if not find in line:
if line.startswith("This is the"):
line = newbasecase + line
我收到“未定义名称'base_num'的错误”,是否有更好的方法来执行此搜索?
答案 0 :(得分:0)
这样的事情呢?查找查找索引和截止索引位置,然后循环浏览行列表并检查截止索引,评估是否存在先前的“查找”变量,如果没有,则添加“添加一行”行并结束新文件。>
find = "Is this found"
find_index = 0
cutoff = "This is the cutoff"
cutoff_index = 0
with open(longStr1) as old_file:
lines = old_file.readlines()
if find in lines:
find_index = lines.index(find)
if cutoff in lines:
cutoff_index = lines.index(cutoff)
with open(endfile1, "w") as new_file:
for num, line in enumerate(lines):
if cutoff in line:
if cutoff_index < find_index:
new_file.write("Adding a line\n")
new_file.write(line)
break
new_file.write(line)