为什么int类型错误?类型错误

时间:2017-05-20 07:32:35

标签: python numpy scipy

我收到了一个错误, TypeError:切片索引必须是整数或无或具有索引方法。 跟踪就像

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()

我认为中心和变量的变量z&amp; 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类型而是浮点类型,因此我可以理解为什么会发生这个错误。但是现在我将这些部分更改为//,所以这些部分是int.So,我该如何解决这个错误呢? / p>

2 个答案:

答案 0 :(得分:2)

变量zq仍为float

center = len(wav) // 2  
cuttime = 0.04         
z = center - cuttime // 2 * fs
q = center + cuttime // 2 * fs

因为cuttimefs都是float,所以整个表达式变为float

您需要将其转换为int

z = int(center - cuttime // 2 * fs)
q = int(center + cuttime // 2 * fs)

答案 1 :(得分:1)

问题可能源于您的变量zq是浮点数。确保将它们转换为int

相关问题