gpt4 book ai didi

python - 将文件打开到数组中,搜索字符串并返回值

转载 作者:行者123 更新时间:2023-11-28 18:55:09 25 4
gpt4 key购买 nike

好吧,我已经为此工作了一段时间,但无法得到它。

我正在制作一个接受文件名和模式的方法。

例如 findPattern(fname, pat)

然后目标是寻找那个模式,在打开的文本文件中说出字符串“apple”,然后通过 [line, beginning character index] 返回它的位置我是 python 的新手,已经被告知了很多方法,但它们要么太复杂,要么我们不允许使用它们,例如索引;我们特别应该使用数组。

我的想法是两个嵌套的 for 循环,外部遍历文本文件数组的每个索引,内部 for 循环比较所需模式的第一个字母。如果找到,内部循环将递增,所以现在它正在检查 apple 中的 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)

最佳答案

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

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

关于python - 将文件打开到数组中,搜索字符串并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3894572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com