2013-02-28 36 views
0

我想从WAV文件返回索引位置。返回索引文件内容的位置

如果发现干草堆中的针头内容,那么我需要返回大海捞针中的针头索引位置。

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

print(haystack.index(needle[:46])); 

我得到一个错误:

Traceback (most recent call last): 
    File "test.py", line 1, in <module> 
    haystack = open("haystack.wav",'r').read() 
    File "C:\Python33\lib\encodings\cp1252.py", line 23, in decode 
    return codecs.charmap_decode(input,self.errors,decoding_table)[0] 
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 5: character maps to <undefined> 

它的工作我做这在PHP中时:

​​
+1

您正在以文本形式阅读文件。你应该将它作为带有'rb'模式的字节读取。 (但是'index'不能按预期工作。) – Ryan 2013-02-28 17:52:01

+0

那么像我在PHP中所做的解决方案是什么?它的工作。 – 2013-02-28 17:52:29

回答

3

如果你读了文件作为二进制在Python 3下使用'rb'你会得到bytes对象。然后你可以使用.index

haystack = open("haystack.wav", 'rb').read() 
needle = open("needle.wav", 'rb').read() 

print(haystack.index(needle[:46])) 

例子:

>>> b'hello world'.index(b'world') 
6 
>>> b'hello world'.index(b'goodbye') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: substring not found 
+0

谢谢,它似乎在Python 2上工作...所以它是Python 3上的一个错误? – 2013-03-01 14:07:31

+0

在我的Python 3.2和Python 3.3中正常工作。 – nneonneo 2013-03-01 14:26:12

-1

haystack = open("haystack.wav",'rb').read()就足够了。然而,我从来没有尝试阅读php中的.wav文件,所以我不知道python和php是否具有相同的二进制编码结构。

>>> a = open("A24.wav", "rb").read() 
>>> a[:100] 
'RIFF\xf4\xe9\x01\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00D\xac\x00\x00\x88X\x01\x00\x02\x00\x10\x00data\xd0\xe9\x01\x00\xff\xff\x01\x00\xff\xff\x01\x00\xff\xff\x01\x00\xff\xff\x01\x00\xff\xff\x01\x00\xfe\xff\x04\x00\xfc\xff\x04\x00\xfc\xff\x02\x00\x00\x00\xfe\xff\x04\x00\xfb\xff\x05\x00\xfc\xff\x02\x00\xff\xff\x00\x00\x01\x00\xfe\xff\x04\x00' 
>>> 

,你想找到“大海捞针”,从“针”相匹配的字符串,可以使用正则表达式做字符串的指标:

import re 

haystack = open("haystack.wav", "rb").read() 
needle = open("needle.wav", "rb").read() 

regex = re.compile(needle[:46]) 
match = regex.search(haystack) 

if match: 
    print match.start() 
+1

索引必须工作。 – 2013-02-28 18:21:05

+0

索引编制确实有效。 – thkang 2013-02-28 18:39:22

0

这是怎样的一个烂摊子,由于蟒蛇路交汇处的这取决于它们是如何在对象访问的字节与整数。 Here is a bit about that。我通过将一个mp3文件写入一个新文件两次来测试这一点。一个观察结果是,如果您的针头中有元数据,则需要在比较长文件之前将其剥离。在我的例子中,针头“编码有跛脚......”。如果你想把这整首歌匹配到更长的那一首,那么就不会有匹配。

def findneedle(bin1, bin2): 
    with open(bin2,'rb') as haystack: 
    with open(bin1,'rb') as needle: 
     n = needle.read() 
     h = [] 
     EOF = None 
     while EOF != b'': 
     EOF = haystack.read(1000) 
     h.append(EOF) 
     if (n in b''.join(h)): 
      h = h[:-1] 
      haystack.seek(haystack.tell() - 1000) 
      while EOF != b'': 
      EOF = haystack.read(1) 
      h.append(EOF) 
      if (n in b''.join(h)): 
       return haystack.tell() - len(n) 

index = findneedle('a.mp3','b.mp3') 
+0

试图使用一个deque真的把我扔在这里。 nneonneo的方法非常有用。我将在这里离开我的对比,以快速和简单的方法。 – Octipi 2013-02-28 21:04:41