Created
August 14, 2011 10:32
-
-
Save joshz/1144779 to your computer and use it in GitHub Desktop.
find string in file using just read(1)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cProfile | |
import pstats | |
def meth(): | |
check = 'abst' | |
c=1 | |
r=1 | |
location = (-1, -1) | |
with open("temp.txt", 'rb') as p: | |
ch = p.read(1) | |
while(ch != ""): | |
if ch == check[0]: | |
st = p.read(len(check)-1) | |
if ch+st == check: | |
location = (r, c) | |
break | |
else: | |
p.seek(-len(check)+1, 1) | |
ch = p.read(1) | |
#print("-- {:<2} {:<4}".format(ch, ord(ch))) | |
c+=1 | |
if ch == '\n': | |
c=0 | |
r+=1 | |
print("loc: {}, {}".format(*location)) | |
#import mmap | |
#with open('temp.txt', 'rb') as f: | |
# m = mmap.mmap(f.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) | |
# position = m.index('abst') | |
def meth2(): | |
string = "abst" | |
f = open("temp.txt", "rb") | |
f.seek(0) | |
location = (-1, -1) | |
row = 1 | |
col = 0 | |
cont = 1 | |
idx = 0 | |
while True: | |
c = f.read(1) | |
col += 1 | |
if c == '': | |
break | |
if c == string[idx]: | |
idx += 1 | |
else: | |
idx = 0 | |
if c == '\n': | |
col = 0 | |
row += 1 | |
if idx == len(string): | |
location = (row, col-len(string)+1) | |
break | |
print location | |
def meth3(): | |
string = "abst" | |
f = open("temp.txt", "rb") | |
f.seek(0) | |
cont = 1 | |
idx = 0 | |
while True: | |
c = f.read(1) | |
if c == '': | |
break | |
if c == string[idx]: | |
idx += 1 | |
else: | |
idx = 0 | |
if idx == len(string): | |
print "Found" | |
break | |
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 | |
def meth4(): | |
with open("temp.txt", 'rb') as f: | |
print find(f, "abst") | |
def main(): | |
cProfile.run("meth()", "f1") | |
cProfile.run("meth2()", "f2") | |
cProfile.run("meth3()", "f3") | |
cProfile.run("meth3()", "f4") | |
p1 = pstats.Stats("f1") | |
p2 = pstats.Stats("f2") | |
p3 = pstats.Stats("f3") | |
p4 = pstats.Stats("f4") | |
p1.sort_stats('cumulative').print_stats(15) | |
p2.sort_stats('cumulative').print_stats(15) | |
p3.sort_stats('cumulative').print_stats(15) | |
p4.sort_stats('cumulative').print_stats(15) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://stackoverflow.com/questions/7052883/how-to-find-substring-in-file/