我收到一个错误, 类型错误:切片索引必须是整数或 None 或具有 index 方法。 回溯就像
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)
关于python - 为什么会出现int类型错误?类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083168/