Python(八) 正則表達式與JSON


一、初識正則表達式

正則表達式 是一個特殊的字符序列,一個字符串是否與我們所設定的這樣的字符序列,相匹配

快速檢索文本、實現替換文本的操作

json(xml) 輕量級 web 數據交換格式

import re

a='C|C++|Java|C#||Python|Javascript'
 
r= re.findall('Python',a)
print(r)

if len(r) > 0:
    print('字符串中包含Python')
else:
    print('No')

['Python']
字符串中包含Python

 

二、元字符與普通字符

import re

a='C0C++7Java8C#9Python6Javascript'

r= re.findall('\d',a)
print(r)

b=''
for x in a:
    try:
        int(x)
        b +=x+','
    except :
        pass

print(b)

結果:
['0', '7', '8', '9', '6']
0,7,8,9,6,
'Python' 普通字符 '\d' 元字符
 

三、字符集

import re

#找出中間一個字符不是C 和F的 單詞
s = 'abc, acc, adc, aec, afc, ahc'

r = re.findall('a[^cf]c', s)  #[a-z] [cf]
print(r)

結果:
['abc', 'adc', 'aec', 'ahc']

 

四、概括字符集

#\d 數字  \D 字母
#\w  數字和字母 =[a-zA-Z0-9_]  \W 
#\s  空白字符  \S
a='python 11\t11java&678p\nh\rp'

r = re.findall('\s', a)
print(r)


結果:
[' ', '\t', '\n', '\r']

 

五、數量詞

a='python 1111java&678php'

r = re.findall('[a-z]{3,6}', a)
print(r)

結果:
['python', 'java', 'php']

 

六、貪婪與非貪婪

a='python 1111java&678php'

r = re.findall('[a-z]{3,6}?', a)
#貪婪 與 非貪婪 ?

print(r)

結果:
['pyt', 'hon', 'jav', 'php']

 

七、匹配0次1次或者無限多次

# * 匹配0次或者無限多次
# + 匹配1次或者無限多次
# ? 匹配0次或者1次

a='pytho0python1pythonn2pythonw'

r = re.findall('python*', a)

print(r)

結果:
['pytho', 'python', 'pythonn', 'python']

 

八、邊界匹配符

qq = '12345678'
# 4~8 
r =  re.findall('^\d{4,8}$', qq)
print(r)

a = '123456789'
# 4~8  ^規則$ ^開頭 $結尾
e =  re.findall('^\d{4,8}$', a)
print(e)

結果:
['12345678']
[]

 

九、組

# () 組 

a = 'pythonpythonpythonpythonpython'
# 
r =  re.findall('(python){3}', a)
print(r)

結果:
['python']  代表存在一組(pythonpythonpython) 這樣的數據

 

十、匹配模式參數

# I | S 忽略大小寫 | 匹配所有字符

lanuage = 'PythonC#\nJavaPHP'

r = re.findall('c#.{1}', lanuage,re.I | re.S)

print(r)


結果:
['C#\n']

 

十一、re.sub正則替換

搜索替換

def convert(value):
    matched = value.group()
    # print(value) <_sre.SRE_Match object; span=(6, 8), match='C#'>
    return '!!'+matched+'!!'


lanuage = 'PythonC#JavaC#PHPC#'

# r = re.sub('C#', 'GO', lanuage, 1) 返回結果: PythonGOJavaC#PHPC#
# s=lanuage.replace('C#', 'GO')
r = re.sub('C#', convert, lanuage)  #傳入參數
print(r)

結果:
Python!!C#!!Java!!C#!!PHP!!C#!!

 

十二、把函數作為參數傳遞

def convert(value):
    matched = value.group() #拿到對象的值
    # print(value) <_sre.SRE_Match object; span=(6, 8), match='C#'>
    if int(matched) >=6 :
        return '9'
    else:
        return '0'

lanuage = 'A8C3721D86'

r = re.sub('\d', convert, lanuage)
print(r)

#
A9C0900D99

 

十三、search與match函數

s = 'A8C3721D86'
# None 從開頭開始匹配 假如沒有找到相應的匹配結果 返回None 只匹配一次
r = re.match('\d', s) 
print(r) #None

#搜索這個字符串 一旦找到第一個滿足匹配的結果就返回 只匹配一次
r1 = re.search('\d', s)
print(r1) #<_sre.SRE_Match object; span=(1, 2), match='8'>
print(r1.group()) #8
print(r1.span()) # (1, 2)

r2 = re.findall('\d', s)
print(r2)  #['8', '3', '7', '2', '1', '8', '6']

 

十四、group分組

#提取life 和python 之間的值
s = 'life is short,i use python'
#None
r = re.search('life.*python', s)
print(r.group()) #life is short,i use python group(組號)

r = re.search('life(.*)python', s)
print(r.group(0)) #life is short,i use python group(組號)
print(r.group(1)) # is short,i use

#group(0)  一種特殊情況 匹配正則表達式完整的結果

r = re.findall('life(.*)python', s)
print(r) #[' is short,i use ']

 

s = 'life is short,i use python, i love python'

r = re.search('life(.*)python(.*)python', s)
print(r.group(0)) # life is short,i use python, i love python 
print(r.group(1)) # is short,i use
print(r.group(2)) # , i love

print(r.group(0,1,2)) #('life is short,i use python, i love python', ' is short,i use ', ', i love ')

print(r.groups()) # (' is short,i use ', ', i love ')

 

十五、一些關於學習正則的建議

#\d 數字  \D 字母
#\w  數字和字母 =[a-zA-Z0-9_]  \W 
#\s  空白字符  \S
# .  匹配除了換行符\n之外其他所有字符
# * 匹配0次或者無限多次
# + 匹配1次或者無限多次
# ? 匹配0次或者1次
# () 組 
# I | S 忽略大小寫 | 匹配所有字符

 

python :爬蟲,數據處理

十六、理解JSON

JSON  是一種輕量級的數據交換格式

字符串是JSON的表現形式

符合 JSON 格式的字符串叫做 JSON 字符串

{"name":"qiyue"}

JSON VS XML

優勢:

跨語言交換數據

易於閱讀

易於解析

網絡傳輸效率高

 

十七、反序列化

import json

# JSON object array
json_str = '{"name":"qiyue","age":18}'
s =  json.loads(json_str)

# dict
#反序列化
s =  json.loads(json_str) #load()  把json 的數據類型 轉換為我們自己語言的數據類型
print(type(s)) #<class 'dict'>
print(s) #{'name': 'qiyue', 'age': 18}
print(s['name']) # qiyue


json_str = '[{"name":"qiyue","age":18},{"name":"qiyue","age":18}]'
s =  json.loads(json_str)
print(type(s)) # <class 'list'>
print(s) # [{'name': 'qiyue', 'age': 18}, {'name': 'qiyue', 'age': 18}]

 

JSON     Python
object   dict
array    list
string   str
number   int
number   float
true     True
false    False
null     None

 

十八、序列化

#序列化 為json

student = [
    {"name":"qiyue","age":18, 'flag':False},
    {"name":"python","age":18}
]


json_str =  json.dumps(student)
print(type(json_str)) # <class 'str'>
print(json_str) #[{"name": "qiyue", "age": 18, "flag": false}, {"name": "python", "age": 18}]

 

十九、小談JSON、JSON對象與JSON字符串

JSON 是一種輕量級的數據交換格式

JSON對象 局限於語言

JSON字符串 

JSON 有自己的數據類型

雖然它和JavaScript  的數據類型有些相似 但是他們不是一種語言 

 

ECMASCRIPT一個標准  JavaScript   ActionScription  JSON 實現標准的一種方案

REST 服務

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM