Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

encoding - Python library for converting plain text (ASCII) into GSM 7-bit character set?

Is there a python library for encoding ascii data to 7-bit GSM character set (for sending SMS)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is now :)

Thanks to Chad for pointing out that this wasn't quite right

Python2 version

# -*- coding: utf8 -*- 
gsm = (u"@£$¥èéùìò?
??
??Δ_ΦΓΛΩΠΨΣΘΞx1b???é !"#¤%&'()*+,-./0123456789:;<=>"
       u"??ABCDEFGHIJKLMNOPQRSTUVWXYZ???ü§?abcdefghijklmnopqrstuvwxyz???üà")
ext = (u"````````````````````^```````````````````{}`````\````````````[~]`"
       u"|````````````````````````````````````€``````````````````````````")

def gsm_encode(plaintext):
    res = ""
    for c in plaintext:
        idx = gsm.find(c)
        if idx != -1:
            res += chr(idx)
            continue
        idx = ext.find(c)
        if idx != -1:
            res += chr(27) + chr(idx)
    return res.encode('hex')

print gsm_encode(u"Hello World")

The output is hex. Obviously you can skip that if you want the binary stream

Python3 version

# -*- coding: utf8 -*- 
import binascii
gsm = ("@£$¥èéùìò?
??
??Δ_ΦΓΛΩΠΨΣΘΞx1b???é !"#¤%&'()*+,-./0123456789:;<=>?"
       "?ABCDEFGHIJKLMNOPQRSTUVWXYZ???ü§?abcdefghijklmnopqrstuvwxyz???üà")
ext = ("````````````````````^```````````````````{}`````\````````````[~]`"
       "|````````````````````````````````````€``````````````````````````")

def gsm_encode(plaintext):
    res = ""
    for c in plaintext:
        idx = gsm.find(c);
        if idx != -1:
            res += chr(idx)
            continue
        idx = ext.find(c)
        if idx != -1:
            res += chr(27) + chr(idx)
    return binascii.b2a_hex(res.encode('utf-8'))

print(gsm_encode("Hello World"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...