2013-02-28 105 views
0

来自PHP背景,我正在学习如何使用Python。返回索引位置

我想回报指数的位置,如果含量在haystackneedle

haystack= open("haystack.wav",'r') 
needle = open("needle.wav",'r') 
nedOffset = needle.read()[:46] 

print(haystack.index(nedOffset)) 

它似乎并没有找到工作,我得到一个错误:

Traceback (most recent call last): 
    File "test.py", line 5, in <module> 
    print(haystack.index(ned[:46])) 
AttributeError: '_io.TextIOWrapper' object has no attribute 'index' 

如何解决?

在PHP中,我会做:

$needle = file_get_contents("needle.wav", false, null, 46); 
$haystack = file_get_contents("heystack.wav"); 
echo strpos($haystack,$needle); 

回答

2

你需要从haystack字符串中读取,而不只是needle。喜欢的东西:

haystack= open("haystack.wav",'r').read() 

with open("haystack.wav",'r') as inf: 
    haystack = inf.read() 
+0

哎呀。完全忘了干草堆 – 2013-02-28 17:30:20

+0

现在我得到了不同的错误:在文件“C:\ Python33 \ lib \ encodings \ cp1252.py”中,第23行解码 返回codecs.charmap_decode(input,self.errors,decode_table)[ 0] UnicodeDecodeError:'charmap'编解码器无法解码位置5中的字节0x8f:字符映射到' – 2013-02-28 17:33:49

+0

@ I'll-Be-Back:这是一个完全不同的问题,需要一个不同的问题。 (此外,这不可能是完整的追溯,因为它没有显示出现在哪条线上)。 – 2013-02-28 17:39:27