如何使用.txt文件中的二进制输入绘制PCM波形

2024-04-25 22:04:08 发布

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

在我的例子中,我将有一个PCM.txt文件,其中包含PCM数据的二进制表示,如下所示

[1. 1. 0. 1. 0. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1. 0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1. 0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 1.]

1的意思是二进制1

0表示二进制0

这只是100个数据样本

  1. 是否可以实现一个python代码,该代码将读取此PCM.txt作为输入,并使用matplotlib绘制此PCM数据?你能给我一些实现这个场景的提示吗
  2. 这个绘制的图形会像一个方波吗

Tags: 文件数据代码txt图形matplotlib场景二进制
1条回答
网友
1楼 · 发布于 2024-04-25 22:04:08

我想你想要这个:

import matplotlib.pyplot as plt 
import numpy as np

x = np.arange(100)
y = [1.,1.,0.,1.,0.,1.,1.,1.,1.,1.,0.,1.,1.,1.,1.,1.,1.,1.,0.,1.,1.,1.,0.,1.,0.,1.,0.,1.,0.,0.,1.,0.,0.,0.,0.,0.,1.,0.,0.,0.,0.,0,0.,0.,1.,0.,0.,1.,0.,1.,0.,1.,0.,1.,0.,1.,1.,1.,1.,1.,0.,1.,1.,1.,1.,1.,1.,1.,0.,1.,1.,1.,0.,1.,0.,1.,0.,1.,0.,0.,1.,0.,0.,0.,0.,0.,1.,0.,0.,0.,0.,0.,0.,0.,1.,0.,0.,1.,0.,1.]

plt.step(x, y)
plt.show() 

enter image description here

如果在读取文件时遇到问题,可以使用正则表达式查找类似数字的内容:

import matplotlib.pyplot as plt 
import numpy as np
import re

# Slurp entire file
with open('data') as f:
    s = f.read()

# Set y to anything that looks like a number
y = re.findall(r'[0-9.]+', s)

# Set x according to number of samples found
x = np.arange(len(y))

# Plot that thing
plt.step(x, y)
plt.show() 

关键字:Python、PCM、PCM信号、绘图、Matplotlib、正则表达式

相关问题 更多 >