我收到一个错误,TypeError: slice indices must be integers or None or have an index method 。追溯就像
Traceback (most recent call last):
File "test.py", line 24, in <module>
wavdata = wav[z:q]
TypeError: slice indices must be integers or None or have an __index__ method
我的代码是
#coding:utf-8
import wave
import numpy as np
from pylab import *
def wavread(filename):
wf = wave.open(filename, "r")
fs = wf.getframerate()
x = wf.readframes(wf.getnframes())
x = np.frombuffer(x, dtype="int16") / 32768.0 # (-1, 1)に正規化
wf.close()
return x, float(fs)
if __name__ == "__main__":
wav, fs = wavread("3_7_9.wav")
t = np.arange(0.0, len(wav) / fs, 1/fs)
center = len(wav) // 2
cuttime = 0.04
z = center-cuttime // 2*fs
q= center + cuttime // 2*fs
wavdata = wav[z:q]
time = t[z:q]
plot(time * 1000, wavdata)
xlabel("time [ms]")
ylabel("amplitude")
savefig("waveform.png")
show()
我认为 center & z & q 的变量是 int 类型,所以我真的不明白为什么会发生这个错误。首先,我写了这部分
if __name__ == "__main__":
wav, fs = wavread("3_7_9.wav")
t = np.arange(0.0, len(wav) / fs, 1/fs)
center = len(wav) / 2
cuttime = 0.04
z = center-cuttime / 2*fs
q= center + cuttime / 2*fs
wavdata = wav[z:q]
time = t[z:q]
plot(time * 1000, wavdata)
xlabel("time [ms]")
ylabel("amplitude")
savefig("waveform.png")
show()
所以这些除法部分不是int类型而是float类型,因此我可以理解为什么会发生这个错误。但现在我把这些部分改成了//,所以这些部分是int。那么,我该如何解决这个错误?
变量z
和q
仍然float
center = len(wav) // 2
cuttime = 0.04
z = center - cuttime // 2 * fs
q = center + cuttime // 2 * fs
因为两者cuttime
和fs
是float
,因此整个表达式变为float
。
你需要投它int
喜欢
z = int(center - cuttime // 2 * fs)
q = int(center + cuttime // 2 * fs)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句