Python 2.7 如何提取文件中文本中间的块 如何提取文本中间的一个块。
例如:Python 2.7 如何提取文件中文本中间的块 如何提取文本中间的一个块。,python-2.7,Python 2.7,例如: User authority -------------- Subscriber number = 189159 Call-out authority = Intra-office = Local = Local toll
User authority
--------------
Subscriber number = 189159
Call-out authority = Intra-office
= Local
= Local toll
= National toll
= International toll
= Intra-Centrex
= Outgoing Centrex
= Intra-office national toll
= Intra-office international toll
= Intra-centrex local toll
= Intra-centrex national toll
= Intra-centrex international toll
= Intra-office local toll
= Customize call-out authority 1
= Customize call-out authority 2
= Customize call-out authority 3
= Customize call-out authority 4
= Customize call-out authority 7
= Customize call-out authority 9
= Customize call-out authority 10
= Customize call-out authority 11
= Customize call-out authority 12
= Customize call-out authority 13
= Customize call-out authority 14
= Customize call-out authority 15
= Customize call-out authority 16
Call-in authority = Intra-office
= Local
= Local toll
= National toll
= International toll
= Intra-Centrex
= Incoming Centrex
= Intra-office national toll
= Intra-office international toll
= Intra-centrex local toll
= Intra-centrex national toll
= Intra-centrex international toll
= Intra-office local toll
= Customize call-in authority 1
= Customize call-in authority 2
= Customize call-in authority 3
= Customize call-in authority 4
= Customize call-in authority 5
= Customize call-in authority 6
= Customize call-in authority 7
= Customize call-in authority 8
= Customize call-in authority 9
= Customize call-in authority 10
= Customize call-in authority 11
= Customize call-in authority 12
= Customize call-in authority 13
= Customize call-in authority 14
= Customize call-in authority 15
= Customize call-in authority 16
Call-in Barring Authority = NULL
K value = K0
我只想提取以调出权限=Intra-office开始的块,直到调出禁止权限=NULL
这是我的代码:
begin=' Call-out authority ='
end=' Call-in Barring Authority ='
with open("data.txt", "r") as f:
t = f.read()
i = t.find(begin)
j=t.startswith(end)
print(t[i:j])
data.txt是一个文件
谢谢大家 为什么不使用
j=t.find(end)
而不是j=t.startswith(end)
?Startswith在本例中不起作用,因为end
字符串的开头可能比您键入的空格多。您可以更好地匹配正则表达式(查看import re
),但是find
似乎在这里起作用。为什么不使用j=t.find(end)
而不是j=t.startswith(end)
?Startswith在本例中不起作用,因为end
字符串的开头可能比您键入的空格多。您可以更好地匹配正则表达式(查看import re
),但是find
似乎在这里完成了它的工作。您只需逐行阅读,直到找到开始
,然后找到结束
:
begin=' Call-out authority ='
end=' Call-in Barring Authority ='
with open("data.txt", "r") as f:
for t in f:
if t.startswith(beg): break
print t
for t in f:
if t.starstwith(end): break
print t,
您只需逐行阅读,直到找到
开始
,然后再找到结束
:
begin=' Call-out authority ='
end=' Call-in Barring Authority ='
with open("data.txt", "r") as f:
for t in f:
if t.startswith(beg): break
print t
for t in f:
if t.starstwith(end): break
print t,