2013-02-28 53 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