0

文本文件包含

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 段中找到 Intranet 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
4

1 回答 1

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
于 2012-08-04T11:46:58.750 回答