通过网纹在R中创建python列表

时间:2019-03-29 15:22:35

标签: python r reticulate

我想通过R中的reticulate使用python分割wave文件,从Python, How to split a .wav file into multiple .wav files中提取示例脚本

 from pydub import AudioSegment
    t1 = t1 * 1000 #Works in milliseconds
    t2 = t2 * 1000
    newAudio = AudioSegment.from_wav("oldSong.wav")
    newAudio = newAudio[t1:t2]
    newAudio.export('newSong.wav', format="wav")

我也使用R做了如下操作:

library(dplyr)
library(tidyr)
library(reticulate)
use_python('/usr/bin/python3',required = TRUE)
py_config()
pydub.py <- import('pydub')
time.start <- as.numeric(data.df.st02[loop,'time_start'])*1000
time.end <- as.numeric(data.df.st02[loop,'time_end'])*1000
new.audio <- pydub.py$AudioSegment$from_wav('142533.wav')

但是返回了以下错误:

> new.audio[1:2]
 Error in py_call_impl(callable, dots$args, dots$keywords) : 
  TypeError: can only concatenate list (not "int") to list 

有人可以启发我如何用R编写[t1:t2]吗?

1 个答案:

答案 0 :(得分:3)

python子集运算符是__getitem__方法的包装,而:是创建slice对象的包装。您必须导入builtins模块。试试这个:

require(reticulate)
use_python('/usr/bin/python3',required = TRUE)
pydub.py <- import('pydub', convert=FALSE)
pybuiltins <- import_builtins(convert=FALSE)
new.audio <- pydub.py$AudioSegment$from_wav('142533.wav')
#important: time.start and time.end must be integer
time.start <- as.integer(1*1000)
time.end <- as.integer(2*1000)
#create a slice object
sl<-pybuiltins$slice(time.start,time.end)
new.audio_split<-new.audio$`__getitem__`(sl)
new.audio_split
#<pydub.audio_segment.AudioSegment>