文本文件包含
paragraph 1:
01 internet 1
02 intranet 2
paragraph 2:
03 internet 1
04 intranet 2
paragraph 3:
05 internet 1
06 intranet 2
paragraph 4:
07 internet 1
08 intranet 2
我想使用python在第2段中找到内联网。
这是我到目前为止所做的:
file = open( "c:\file.txt", "r" ).readlines()
var = raw_input("enter the value")
var1 = "paragraph 1:"
for line in file:
if re.search(var1, line,re.IGNORECASE):
print re.search(var, line,re.IGNORECASE)
print "found", line
count=line for line in file:
if re.search(var, line,re.IGNORECASE):
print "value=", line
答案 0 :(得分:1)
假设您只想搜索指定的部分,这应该有效:
def find(file, paragrapgh_number, search_string):
paragraph = 'paragraph {}'.format(paragrapgh_number)
for line in file:
if line.find(paragraph) >= 0:
break
for line in file:
if line.find(search_string) >=0:
print('Found:', line)
elif line.find('paragraph') >= 0:
print('Not found')
return
with open( "./test.txt", "r" ) as file:
find(file, 2, 'intranet 2')
>>>Found: 04 intranet 2
如果在指定的部分中找不到该字符串,则会显示
>>>Not Found