Как разделить данные с помощью Python? - PullRequest
0 голосов
/ 09 мая 2019

Я создал скрипт на Python для чтения данных с последовательного порта.Но я застрял с разделенной частью.Я новичок в этом языке программирования.

Я хотел бы сохранить параметры внутри переменных.

import serial 
import re
from serial import Serial
ser = serial.Serial('/dev/ttyACM0')
print(ser.isOpen) #True
serial_data = ser.readline()
print(serial_data)

Выход : b 'H: 209,44 R: 4,88 P: -168,00 A: 1 M0 G3 S: 0 T: 0,00 \ r \ n

encoding = serial_data.decode(encoding = "ascii", errors = "ignore")

encoding_split = encoding.split(" ")

Выход : ['', 'H: 209.44', 'R: 4.88', 'P: -168.00', 'A: 1', 'M0', 'G3', 'S: 0 ',' T: 0.00 \ r \ n ']

Неправильная часть: Теперь я хотел бы сохранить значения внутри переменной

H =(re.search(r'(?<=H:)\w+', encoding_split)
R =(re.search(r'(?<=R:)\w+', encoding_split)
P =(re.search(r'(?<=P:)\w+', encoding_split)
A =(re.search(r'(?<=A:)\w+', encoding_split)
M =(re.search(r'(?<=M)\w+',  encoding_split)
G =(re.search(r'(?<=G)\w+',  encoding_split)
S =(re.search(r'(?<=S:)\w+', encoding_split)
T =(re.search(r'(?<=T:)\w+', encoding_split)
TypeError: expected string or bytes-like object

Ответы [ 2 ]

0 голосов
/ 09 мая 2019

Пожалуйста, попробуйте следующий код



# serial_data contains the data in binary format
serial_data =  b' H:209.44 R:4.88 P:-168.00 A:1 M0 G3 S:0 T:0.00\r\n'

# We convert byte data to string as below
serial_data_string = serial_data.decode('utf-8')

# We remove white space from both ends
serial_data_string = serial_data_string.strip()

# Convert the string to array having pair of Key and value
paired_data = serial_data_string.split(' ')

# We Create a dict to store the ouput
output = {}

# We iterate over each item in array and extract key and value
# and set the to dict

for each_key_value_pair in paired_data:
    key_value_splitted = each_key_value_pair.split(':')
    key = key_value_splitted[0]
    value = 0
    if len(key_value_splitted) > 1:
        value = float(key_value_splitted[1])

    # We set this value to ouput variable

    output[key] = value


print(output)

# Now you can access outputs like 
A = output['A']
B = output['R']


0 голосов
/ 09 мая 2019

Проблема была с RegEx, я думаю.

Я попробовал, пожалуйста, посмотрите

import serial
import re
from serial import Serial

def main():
    # ser = serial.Serial('/dev/ttyACM0')
    # print(ser.isOpen) #True
    # serial_data = ser.readline()
    # print(serial_data)
    # encoding = serial_data.decode(encoding = "ascii", errors = "ignore")
    # encoding_split = encoding.split(" ")
    encoding_split="H:209.44', 'R:4.88', 'P:-168.00', 'A:1', 'M0', 'G3', 'S:0', 'T:0.00\r\n"
    H=(re.search(r"(?<=H:)(\-*\s*[0-9]+\.*[0-9]*)", encoding_split))
    R=(re.search(r"(?<=R:)(\-*\s*[0-9]+\.*[0-9]*)", encoding_split))
    P=(re.search(r"(?<=P:)(\-*\s*[0-9]+\.*[0-9]*)", encoding_split))
    A=(re.search(r"(?<=A:)(\-*\s*[0-9]+\.*[0-9]*)", encoding_split))
    M=(re.search(r"(?<=M)(\-*\s*[0-9]+\.*[0-9]*)",  encoding_split))
    G=(re.search(r"(?<=G)(\-*\s*[0-9]+\.*[0-9]*)",  encoding_split))
    S=(re.search(r"(?<=S:)(\-*\s*[0-9]+\.*[0-9]*)", encoding_split))
    T=(re.search(r"(?<=T:)(\-*\s*[0-9]+\.*[0-9]*)", encoding_split))

    print(H.group(0))
    print(R.group(0))
    print(P.group(0))
    print(A.group(0))
    print(M.group(0))
    print(G.group(0))
    print(S.group(0))
    print(T.group(0))


if __name__ == '__main__':
    main()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...