Ok, Iβve been working on this for a while and can't get it.
I am making a method that accepts a file name and template.
For example, findPattern (fname, pat)
Then the goal is to look for this pattern, for example, the string "apple" in the opened text file and return its location by [string, starting character index] I am new to python and have been told many ways, but they are either too complicated or we are not allowed to use them, for example index; we specifically must use arrays.
My thoughts were two nested for loops, each index of the textfile array goes outside, and the inner for loop compares the first letter of the desired pattern. If found, the inner loop will be processed, so now it checks p in the apple and text file.
One of the main problems is that I cannot get the file into an array, I was able to execute only a whole line.
Here I have something, although it doesnβt quite work. I just experimented with .tell to show me where it is, but it is always at 141, which I believe is EOF, but I have not tested it.
print
fname = raw_input('Enter filename: ')
pattern = raw_input('Enter pattern: ')
def findPattern(fname, pat):
f = open(fname, "r")
for line in f:
if pat in line:
print "Found it @ " +(str( f.tell()))
break
else:
print "No esta..."
print findPattern(fname, pattern)
EDIT:
fname = raw_input('Enter filename: ')
pattern = raw_input('Enter pattern: ')
def findPattern(fname, pat):
arr = array.array('c', open(fname, 'rb').read())
for i in xrange(len(arr)):
if ''.join(arr[i:i+len(pat)]) == pat:
print 'Found @ %d' % i
print
findPattern(fname, pattern)
So, from the new code that has been replaced above, I get what is lower. I know this is something dumb, like an array that is not declared, but I'm not quite sure of the python syntax for this, does the array need to have a given size when it is declared?
lynx:desktop $ python hw3.py
Enter filename: declaration.txt
Enter pattern: become
Traceback (most recent call last):
File "hw3.py", line 25, in <module>
findPattern(fname, pattern)
File "hw3.py", line 17, in findPattern
arr = array.array('c', open(fname, 'rb').read())
NameError: global name 'array' is not defined
EDIT:
, ! , .
.
for i in xrange(len(arr)):
if arr[i] == '\n':
linePos = linePos + 1
colPos = i
if ''.join(arr[i:i+len(pat)]) == pat:
resultPos = i - colPos
print 'Found @ %d on line %d' % (resultPos, linePos)