【发布时间】:2011-04-23 02:45:25
【问题描述】:
好的,我已经研究了一段时间,但无法获得它。
我正在制作一个接受文件名和模式的方法。
例如 findPattern(fname, pat)
然后目标是寻找那个模式,在打开的文本文件中说字符串“apple”,然后通过[行,开始字符索引]返回它的位置 我是 python 新手,被告知了很多方法,但它们要么太复杂,要么我们不允许使用它们,例如 index;我们特别应该使用数组。
我的想法是两个嵌套的 for 循环,外部遍历文本文件数组的每个索引,内部 for 循环比较所需模式的第一个字母。如果找到,内部循环将重新进行,因此现在它正在检查苹果中的 p 与文本文件。
一个主要问题是我无法将文件放入数组中,我只能做一整行。
这是我有的东西,虽然不太好用。我只是在试验 .tell 来告诉我它在哪里,但它总是在 141,我相信这是 EOF,但我还没有检查。
#.....Id #
#.....Name
#########################
#my intent was for you to write HW3 code as iteration or
#nested iterations that explicitly index the character
#string as an array; i.e, the Python index() also known as
#string.index() function is not allowed for this homework.
########################
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)
编辑:
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)
所以从上面替换的新代码中,我得到了下面的内容。我知道这有点像未声明的数组,但我不确定python语法,声明数组时不需要设置大小吗?
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
编辑: 并且,完成!多谢你们。 我就是这样弄的。。
#Iterate through
for i in xrange(len(arr)):
#Check for endline to increment linePos
if arr[i] == '\n':
linePos = linePos + 1
colPos = i
#Compare a chunk of array the same size
#as pat with pat itself
if ''.join(arr[i:i+len(pat)]) == pat:
#Account for newline with absolute position
resultPos = i - colPos
print 'Found @ %d on line %d' % (resultPos, linePos)
【问题讨论】:
-
您所拥有的可能也不会被允许,因为
in运算符有点作弊。您的老师似乎希望您手动实现子字符串搜索。 -
要在 Python 2.x 中将文件读入列表(not 数组),请使用
f.readlines()。
标签: python arrays string file search