您的位置:

python下采样代码(python下采样函数)

本文目录一览:

PYTHON语言如何取到声音的频率(其他语言也可行)

先得到时域信号,然后做傅立叶变换,得到频谱。

感觉题主可能对python比较熟悉?那就别换语言了。稍微百度谷歌以下肯定能找到python的傅立叶变换的库。

急!!!!如何通过python制作一个简单的录音机,录制自己的声音采用8k采样,16位量化编码,观察其数值?

#我可以帮你写一段代码,能够录音形成wav文件,不过要分析录音文件的波形,你可以另外找#工具,比如cooledit,也很方便。

from sys import byteorder

from array import array

from struct import pack

import pyaudio

import wave

THRESHOLD = 500

CHUNK_SIZE = 1024

FORMAT = pyaudio.paInt16

RATE = 44100

def is_silent(snd_data):

    "Returns 'True' if below the 'silent' threshold"

    return max(snd_data)  THRESHOLD

def normalize(snd_data):

    "Average the volume out"

    MAXIMUM = 16384

    times = float(MAXIMUM)/max(abs(i) for i in snd_data)

    r = array('h')

    for i in snd_data:

        r.append(int(i*times))

    return r

def trim(snd_data):

    "Trim the blank spots at the start and end"

    def _trim(snd_data):

        snd_started = False

        r = array('h')

        for i in snd_data:

            if not snd_started and abs(i)THRESHOLD:

                snd_started = True

                r.append(i)

            elif snd_started:

                r.append(i)

        return r

    # Trim to the left

    snd_data = _trim(snd_data)

    # Trim to the right

    snd_data.reverse()

    snd_data = _trim(snd_data)

    snd_data.reverse()

    return snd_data

def add_silence(snd_data, seconds):

    "Add silence to the start and end of 'snd_data' of length 'seconds' (float)"

    r = array('h', [0 for i in xrange(int(seconds*RATE))])

    r.extend(snd_data)

    r.extend([0 for i in xrange(int(seconds*RATE))])

    return r

def record():

    """

    Record a word or words from the microphone and 

    return the data as an array of signed shorts.

    Normalizes the audio, trims silence from the 

    start and end, and pads with 0.5 seconds of 

    blank sound to make sure VLC et al can play 

    it without getting chopped off.

    """

    p = pyaudio.PyAudio()

    stream = p.open(format=FORMAT, channels=1, rate=RATE,

        input=True, output=True,

        frames_per_buffer=CHUNK_SIZE)

    num_silent = 0

    snd_started = False

    r = array('h')

    while 1:

        # little endian, signed short

        snd_data = array('h', stream.read(CHUNK_SIZE))

        if byteorder == 'big':

            snd_data.byteswap()

        r.extend(snd_data)

        silent = is_silent(snd_data)

        if silent and snd_started:

            num_silent += 1

        elif not silent and not snd_started:

            snd_started = True

        if snd_started and num_silent  30:

            break

    sample_width = p.get_sample_size(FORMAT)

    stream.stop_stream()

    stream.close()

    p.terminate()

    r = normalize(r)

    r = trim(r)

    r = add_silence(r, 0.5)

    return sample_width, r

def record_to_file(path):

    "Records from the microphone and outputs the resulting data to 'path'"

    sample_width, data = record()

    data = pack('' + ('h'*len(data)), *data)

    wf = wave.open(path, 'wb')

    wf.setnchannels(1)

    wf.setsampwidth(sample_width)

    wf.setframerate(RATE)

    wf.writeframes(data)

    wf.close()

if __name__ == '__main__':

    print("please speak a word into the microphone")

    record_to_file('demo.wav')

    print("done - result written to demo.wav")

怎么使用Python中Pandas库Resample,实现重采样,完成线性插值

#python中的pandas库主要有DataFrame和Series类(面向对象的的语言更愿意叫类) DataFrame也就是

#数据框(主要是借鉴R里面的data.frame),Series也就是序列 ,pandas底层是c写的 性能很棒,有大神

#做过测试 处理亿级别的数据没问题,起性能可以跟同等配置的sas媲美

#DataFrame索引 df.loc是标签选取操作,df.iloc是位置切片操作

print(df[['row_names','Rape']])

df['行标签']

df.loc[行标签,列标签]

print(df.loc[0:2,['Rape','Murder']])

df.iloc[行位置,列位置]

df.iloc[1,1]#选取第二行,第二列的值,返回的为单个值

df.iloc[0,2],:]#选取第一行及第三行的数据

df.iloc[0:2,:]#选取第一行到第三行(不包含)的数据

df.iloc[:,1]#选取所有记录的第一列的值,返回的为一个Series

df.iloc[1,:]#选取第一行数据,返回的为一个Series

print(df.ix[1,1]) # 更广义的切片方式是使用.ix,它自动根据你给到的索引类型判断是使用位置还是标签进行切片

print(df.ix[0:2])

#DataFrame根据条件选取子集 类似于sas里面if、where ,R里面的subset之类的函数

df[df.Murder13]

df[(df.Murder10)(df.Rape30)]

df[df.sex==u'男']

#重命名 相当于sas里面的rename R软件中reshape包的中的rename

df.rename(columns={'A':'A_rename'})

df.rename(index={1:'other'})

#删除列 相当于sas中的drop R软件中的test['col']-null

df.drop(['a','b'],axis=1) or del df[['a','b']]

#排序 相当于sas里面的sort R软件里面的df[order(x),]

df.sort(columns='C') #行排序 y轴上

df.sort(axis=1) #各个列之间位置排序 x轴上

#数据描述 相当于sas中proc menas R软件里面的summary

df.describe()

#生成新的一列 跟R里面有点类似

df['new_columns']=df['columns']

df.insert(1,'new_columns',df['B']) #效率最高

df.join(Series(df['columns'],name='new_columns'))

#列上面的追加 相当于sas中的append R里面cbind()

df.append(df1,ignore_index=True)

pd.concat([df,df1],ignore_index=True)

#最经典的join 跟sas和R里面的merge类似 跟sql里面的各种join对照

merge()

#删除重行 跟sas里面nodukey R里面的which(!duplicated(df[])类似

df.drop_duplicated()

#获取最大值 最小值的位置 有点类似矩阵里面的方法

df.idxmin(axis=0 ) df.idxmax(axis=1) 0和1有什么不同 自己摸索去

#读取外部数据跟sas的proc import R里面的read.csv等类似

read_excel() read_csv() read_hdf5() 等

与之相反的是df.to_excel() df.to_ecv()

#缺失值处理 个人觉得pandas中缺失值处理比sas和R方便多了

df.fillna(9999) #用9999填充

#链接数据库 不多说 pandas里面主要用 MySQLdb

import MySQLdb

conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="mysql",use_unicode=True,charset="utf8")

read_sql() #很经典

#写数据进数据库

df.to_sql('hbase_visit',con, flavor="mysql", if_exists='replace', index=False)

#groupby 跟sas里面的中的by R软件中dplyr包中的group_by sql里面的group by功能是一样的 这里不多说

#求哑变量

dumiper=pd.get_dummies(df['key'])

df['key'].join(dumpier)

#透视表 和交叉表 跟sas里面的proc freq步类似 R里面的aggrate和cast函数类似

pd.pivot_table()

pd.crosstab()

#聚合函数经常跟group by一起组合用

df.groupby('sex').agg({'height':['mean','sum'],'weight':['count','min']})

#数据查询过滤

test.query("0.2

将STK_ID中的值过滤出来

stk_list = ['600809','600141','600329']中的全部记录过滤出来,命令是:rpt[rpt['STK_ID'].isin(stk_list)].

将dataframe中,某列进行清洗的命令

删除换行符:misc['product_desc'] = misc['product_desc'].str.replace('\n', '')

删除字符串前后空格:df["Make"] = df["Make"].map(str.strip)

如果用模糊匹配的话,命令是:

rpt[rpt['STK_ID'].str.contains(r'^600[0-9]{3}$')]

对dataframe中元素,进行类型转换

df['2nd'] = df['2nd'].str.replace(',','').astype(int) df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)

#时间变换 主要依赖于datemie 和time两个包

#其他的一些技巧

df2[df2['A'].map(lambda x:x.startswith('61'))] #筛选出以61开头的数据

df2["Author"].str.replace(".+", "").head() #replace(".+", "")表示将字符串中以””开头;以””结束的任意子串替换为空字符串

commits = df2["Name"].head(15)

print commits.unique(), len(commits.unique()) #获的NAME的不同个数,类似于sql里面count(distinct name)

#pandas中最核心 最经典的函数apply map applymap