“TypeError:字节索引必须是整数或切片,而不是str”将字节转换为int

2024-04-27 07:46:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个不同的程序(ffmpeg)获取下载的youtube视频的长度,以便随机化视频中的特定点。但是,当我尝试执行以下代码时,会出现此错误:

def grabTimeOfDownloadedYoutubeVideo(youtubeVideo):
    process = subprocess.Popen(['/usr/local/bin/ffmpeg', '-i', youtubeVideo], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout, stderr = process.communicate()
    matches = str(re.search(b"Duration:\s{1}(?P<hours>\d+?):(?P<minutes>\d+?):(?P<seconds>\d+\.\d+?),", stdout, re.DOTALL).groupdict()).encode()
    print(matches)
    hours = int(matches['hours'])
    minutes = int(matches['minutes'])
    seconds = int(matches['seconds'])
    total = 0
    total += 60 * 60 * hours
    total += 60 * minutes
    total += seconds
    print(total)

匹配变量将输出到:

b"{'minutes': b'04', 'hours': b'00', 'seconds': b'24.94'}"

所以所有的输出在它的开头都有一个“b”。我该如何去掉“b”并只获取号码?

此处显示完整的错误消息:

Traceback (most recent call last):
  File "bot.py", line 87, in <module>
    grabTimeOfDownloadedYoutubeVideo("videos/1.mp4")
  File "bot.py", line 77, in grabTimeOfDownloadedYoutubeVideo
    hours = int(matches['hours'])
TypeError: byte indices must be integers or slices, not str

Tags: 视频错误stderrstdoutprocessffmpeginttotal
2条回答
matches = str(re.search(b"Duration:\s{1}(?P<hours>\d+?):(?P<minutes>\d+?):(?P<seconds>\d+\.\d+?),", stdout, re.DOTALL).groupdict()).encode()

很奇怪。通过将regex匹配的结果转换为字符串,您将导致错误(因为现在matches['hours']将失败)。

通过将该字符串编码为bytes对象(为什么?),你让事情更复杂了。

matches = re.search(r"Duration:\s(?P<hours>\d+?):(?P<minutes>\d+?):(?P<seconds>\d+\.\d+?),", stdout).groupdict()

应该这样做(尽管我不确定是否使用stdout作为输入..)

你好像有一个byte对象。要使用它,您可以执行以下操作**:

解码:

matches = matches.decode("utf-8")

然后,通过使用^{},将str转换为真正的dict

matches = ast.literal_eval(matches)

然后您可以像平常一样访问匹配项的内容:

int(matches['hours']) # returns 0

**当然,这只是修复了一个错误,正如@Tim指出的那样,这个错误本来就不应该出现在这里。

相关问题 更多 >