【问题标题】:Open file into array, search for string and return value将文件打开到数组中,搜索字符串并返回值
【发布时间】: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


【解决方案1】:

将文本数据放入数组的唯一方法是作为字符:

a = array.array('c', open(filename, 'rb').read())

从那里,您可以简单地对其进行迭代并将每个长度与子字符串相同的子数组转换为要比较的字符串:

for i in xrange(len(a)):
   if ''.join(a[i:i+len(substring)]) == substring:
      print 'Found @ %d!' % i

然而,这是非常不符合 Python 的并且非常缓慢

如果数组是指一个列表(这两个术语在 Python 中的含义非常不同):

pos = 0
for line in open(filename):
    for i in xrange(len(line)):
        if line[i:i+len(substring)] == substring:
           print 'Found @ %d!' % (pos + i)
    pos += len(line) + 2 # 1 if on Linux

这也很慢且不符合 Python 风格,但比前一个选项略逊一筹。如果这些中的任何一个确实是你被要求做的,那么你的老师可能不应该教 Python。 :p

【讨论】:

  • 我需要以某种方式声明数组吗?
  • 实际上,您需要导入它。它是一个模块。 :)
  • 与c中的#import 如此相似?似乎只是“导入数组”?
  • 愚蠢的问题,完美。我喜欢我们不必处理换行符,因为如果我在第一行输入最后一个单词,在第二行输入第一个单词,它不应该找到它,而且不是因为该换行符 \n 字符。另外,我现在可以用它作为计数来查看我在哪条线上,对吧?让我们看看我如何处理它。我能看到的唯一问题是,我们一直保持的字符数,而不是担心哪一行。我相信我需要从每行的 0 开始。
  • 假设您使用第一个版本,i 确实是文件中的“绝对位置”,而不是每行内的偏移量。如果您想要根据行和列而不是文件中的绝对位置来定位,则需要再保留两个计数器(行和列)并在每次 a[i] == '\n' 时增加行并重置列。
猜你喜欢
  • 1970-01-01
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2014-02-13
相关资源
最近更新 更多