【发布时间】:2016-01-26 14:23:57
【问题描述】:
我有一个输入文件,而我必须根据 2 个空白新行提取几行。
例如:文本文件如下所示。
1. Sometext
Sometext
Sometext
2. Sometext
Sometext
Sometext
3. Sometext
Sometext
Sometext
Sometext which is not needed
Sometext which is not needed
Sometext which is not needed
我必须从“1”中提取一个子字符串。对“2”之前的所有人。 以及“2”的第二个子字符串。对“3”之前的所有人。依此类推。我有下面的脚本来获取输出,但它也获取了我不想要的所有“不需要的某些文本”。请看下面的代码:
file_path = open("filename", "r")
content = file_path.read()
size1 = len(content)
start =0
a=1
b=2
end =0
ext =0
while (start<size):
if (end !=-1):
subString = content[content.find(str(a)+".")+0:content.find("\n"+str(b)+".")]
print (subString)
end = content.find(str(b)+".",start)
print ("\n")
a = int(a)+1 # increment to find the next start number
b = int(b)+1 # increment to find the next end number
start = end+1 # continuing to search the next
else:
break
所以,我决定为结束位置找到 2 个连续的空白行,并使用下面的一个,但是没有用。
subString = content[content.find (str(a)+".")+3:content.find("\n\n")]
请帮助,如果您有任何问题,请告诉我。 提前谢谢你。
【问题讨论】:
-
“不需要的某些文本”与其他行有何不同?是在文件末尾还是什么的?
-
您的样本数据格式是否正确?每行之间似乎有 3 个换行符。
-
@GriMel ..“不需要的某些文本”在 2 个新行之后不以数字开头
-
@glibdud .. 抱歉,我尝试使用 2 个换行符进行格式化,但文本都在一行中。所以我不得不以这种方式编辑它。请将此视为仅用 2 行分隔的示例。
-
请看我建议的编辑...这是否准确地代表了数据的样子?
标签: python python-3.x