2011-08-13 4 views
1

read (1) 만 사용하여 이진 파일에서 문자열을 찾는 방법은 무엇입니까? 예를 들어, 파일에 문자열 'abst'의 위치를 ​​찾고 싶습니다 (메모리에로드하지 않고)?파일에서 하위 문자열을 찾는 방법은 무엇입니까?

 
#!/usr/bin/python2 
f = open("/tmp/rr", "rb") 
f.seek(0) 

cont = 1 
while(cont): 
    a1 = f.read(1) 
    if a1 == 'a': 
     a2 = f.read(1) 
     if a2 == 'b': 
      a3 = f.read(1) 
      if a3 == 's': 
       a4 = f.read(1) 
       if a4 == 't': 
        found = True 
        cont = 0 

+2

파일에'aabst'가 있으면 어떻게 될까요? –

+4

왜'read (1)'만을 사용하고 싶습니까? 숙제인가요? – ecik

답변

1

당신은 문자열을 찾을 수-방법을 사용하여 문자열을 찾을 수 있습니다 그것은 작동하지만 매우 원시적이다.

content = file.read() 
name = 'abst' 
if name in content: 
    slice = content.find(name) 
    slice = slice, slice + len(name) 

read(1) -method 절대적으로 무의미하다. #see 편집

편집 : read(1)를 사용

def find(file, name): 
    length = len(name) 
    part = file.read(length) 
    i = 0 
    while True: 
     if part == name: 
      break 
     char = file.read(1) 
     if not char: 
      return 
     part = part[1:] + char 
     i += 1 
    return i, i + length, part 

는 내가 보는 메모리, 더 effiecient은 무의미하지 않습니다. 일정한 메모리 요구 사항 파일 검색

+0

이 접근법은 파일 양에 메모리를 필요로하는데, 검색하는 것만으로는 불필요합니다. – phihag

+0

@philhag :'mmap' 접근 방식도 파일을 메모리에 저장해야합니까? –

+0

제발 이것이 효율적인 노트라고 말하지 마십시오. (편집 참조) –

4

사용 mmap :

import mmap 
with open('/tmp/rr', 'rb') as f: 
    m = mmap.mmap(f.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) 
    position = m.index('abst') 
+0

'found' 대신'position'을 사용하여 업데이트했습니다. 문자열이 발견되지 않으면 결과는 -1이됩니다. – phihag

2

을 윌 당신을 위해이 일? 파일은 대부분의 '가득, 또는 어떤 캐릭터 당신이 너 한테 큰 시간을 빨아 검색하는 문자열의 첫 번째 문자에 해당하는 경우

#!/usr/bin/python 

string = "abst" 
f = open("/tmp/rr", "rb") 
f.seek(0) 

cont = 1 
idx = 0 
while True: 
    c = f.read(1) 
    if c == '': 
     break 
    if c == string[idx]: 
     idx += 1 
    elif c == string[0]: 
     idx = 1 
    else: 
     idx = 0 
    if idx == len(string): 
     print "Found" 
     break 
0

, 그렇지 않으면 꽤 잘 작동합니다.

check = 'abst' 
col=1 
row=1 
location = (-1, -1) 

with open("/tmp/rr", 'rb') as p: 
    ch = p.read(1) 
    while(ch != ""): 
     if ch == check[0]: 
      st = p.read(len(check)-1) 
      if ch+st == check: 
       location = (row, col) 
       break 
      else: 
       p.seek(-len(check)+1, 1) 

     ch = p.read(1) 
     col+=1 

     if ch == '\n': 
      col=0 
      row+=1 

print("loc: {}, {}".format(*location)) 
관련 문제