1. 程式人生 > 其它 >Elasticsearch 7.10 之 Paginate search results

Elasticsearch 7.10 之 Paginate search results

技術標籤:pythonpython

python_study

python基本語法規則

  • 1 python 的作用

    可以在伺服器上使用 Python 來建立 Web 應用程式。
    Python 可以與軟體一起使用來建立工作流。
    Python 可以連線到資料庫系統。它還可以讀取和修改檔案。
    Python 可用於處理大資料並執行復雜的數學運算。
    Python 可用於快速原型設計,也可用於生產就緒的軟體開發。
  • 2 cmd編寫python

  • 3 if 語句

if 5>2:
    print("5>2")

- (1)同一程式碼塊中使用相同數量的空格,否則 Python 會出錯
- (2)#註釋
  • 4 字串:單引號和雙引號皆可

    • (1) “”""""賦值方式(三個雙引號)

    [外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-在這裡插入圖片描述
    yjZAPnBY-1611893496718)(三引號賦值方式.png)]

    • (2)Python 沒有字元資料型別,單個字元就是長度為 1 的字串。
    • (3)len()函式
    a = "Hello, World!"
    print(len(a))
    
    • (4) str.lower()
    • (5) str.upper()
    • (6) str.strip()
    • (7) a = “Hello, World!” print(a.replace(“World”, “Kitty”))
    • (8) a = “hello world” x = “llo” not in a # x = True
  • 5 命名規則


    變數名必須以字母或下劃線字元開頭
    變數名稱不能以數字開頭
    變數名只能包含字母數字字元和下劃線(A-z、0-9 和 _)
    變數名稱區分大小寫(age、Age 和 AGE 是三個不同的變數)
  • 6 多個變數同行賦值

    • x, y, z = “Orange”, “Banana”, “Cherry”
  • 7 print

    • print("hello "+“world”)
    • print(10+“e”)#會出錯
  • 8 global 關鍵字

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)
  • 9 資料型別
    • 獲取資料型別
    x = 10
    print(type(x))
    
文字型別: 	str
數值型別: 	int, float, complex
序列型別: 	list, tuple, range
對映型別: 	dict
集合型別: 	set, frozenset
布林型別: 	bool
二進位制型別: 	bytes, bytearray, memoryview

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-aDkU29rA-1611893496719)(python資料型別.png)]

  • 10 random模組
import random
print(random.randrange(1,10))
  • 11 建構函式建立新變數
    int() - 用整數字面量、浮點字面量構造整數(通過對數進行下舍入),或者用表示完整數字的字串字面量
    float() - 用整數字面量、浮點字面量,或字串字面量構造浮點數(提供表示浮點數或整數的字串)
    str() - 用各種資料型別構造字串,包括字串,整數字面量和浮點字面量
  • 12 字串輸出的format 的方法

    • (1)format() 方法接受不限數量的引數,並放在各自的佔位符中
    quantity = 3
    itemno = 567
    price = 49.95
    myorder = "I want {} pieces of item {} for {} dollars."
    print(myorder.format(quantity, itemno, price))
    
    • (2)python內建方法
    capitalize() 	把首字元轉換為大寫。
    casefold() 	把字串轉換為小寫。
    center() 	返回居中的字串。
    count() 	返回指定值在字串中出現的次數。
    encode() 	返回字串的編碼版本。
    endswith() 	如果字串以指定值結尾,則返回 true。
    expandtabs() 	設定字串的 tab 尺寸。
    find() 	在字串中搜索指定的值並返回它被找到的位置。
    format() 	格式化字串中的指定值。
    format_map() 	格式化字串中的指定值。
    index() 	在字串中搜索指定的值並返回它被找到的位置。
    isalnum() 	如果字串中的所有字元都是字母數字,則返回 True。
    isalpha() 	如果字串中的所有字元都在字母表中,則返回 True。
    isdecimal() 	如果字串中的所有字元都是小數,則返回 True。
    isdigit() 	如果字串中的所有字元都是數字,則返回 True。
    isidentifier() 	如果字串是識別符號,則返回 True。
    islower() 	如果字串中的所有字元都是小寫,則返回 True。
    isnumeric() 	如果字串中的所有字元都是數,則返回 True。
    isprintable() 	如果字串中的所有字元都是可列印的,則返回 True。
    isspace() 	如果字串中的所有字元都是空白字元,則返回 True。
    istitle() 	如果字串遵循標題規則,則返回 True。
    isupper() 	如果字串中的所有字元都是大寫,則返回 True。
    join() 	把可迭代物件的元素連線到字串的末尾。
    ljust() 	返回字串的左對齊版本。
    lower() 	把字串轉換為小寫。
    lstrip() 	返回字串的左修剪版本。
    maketrans() 	返回在轉換中使用的轉換表。
    partition() 	返回元組,其中的字串被分為三部分。
    replace() 	返回字串,其中指定的值被替換為指定的值。
    rfind() 	在字串中搜索指定的值,並返回它被找到的最後位置。
    rindex() 	在字串中搜索指定的值,並返回它被找到的最後位置。
    rjust() 	返回字串的右對齊版本。
    rpartition() 	返回元組,其中字串分為三部分。
    rsplit() 	在指定的分隔符處拆分字串,並返回列表。
    rstrip() 	返回字串的右邊修剪版本。
    split() 	在指定的分隔符處拆分字串,並返回列表。
    splitlines() 	在換行符處拆分字串並返回列表。
    startswith() 	如果以指定值開頭的字串,則返回 true。
    strip() 	返回字串的剪裁版本。
    swapcase() 	切換大小寫,小寫成為大寫,反之亦然。
    title() 	把每個單詞的首字元轉換為大寫。
    translate() 	返回被轉換的字串。
    upper() 	把字串轉換為大寫。
    zfill() 	在字串的開頭填充指定數量的 0 值。
    
  • 13 值為False的表示式

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
  • 14 isinstance()函式
x = 1
isinstance(x,int)
  • 15 << >>運算子

    • 10>>2 表示 10/(2^2)
    • 10<<2 表示 10*2^2
  • 16 python 身份運算子

x = 4
y = 4
x is y
  • 17 成員資格運算子

    • (1)
    x = [1,2,3]
    3 (not) in x
    
    • (2)
    if "apple" in thislist:
    print("Yes, 'apple' is in the fruits list")
    
  • 18 python集合(陣列)

列表(List)是一種有序和可更改的集合。允許重複的成員。
元組(Tuple)是一種有序且不可更改的集合。允許重複的成員。
集合(Set)是一個無序和無索引的集合。沒有重複的成員。
詞典(Dictionary)是一個無序,可變和有索引的集合。沒有重複的成員
  • 19 list方法

    • (1) append
    • (2) extend
    • (3) len(list)
    • (4) lst.insert(index,value)
    • (5) lst.remove()
    • (6) lst.pop(index)
    • (7) del lst[index]/del lst
    • (8) lst.clear()
    • (9) 兩個列表的連線方式
      • 1 lst1 + lst2
      • 2 lst1.extend(lst2)
    • (10) 內建方法
    append() 	在列表的末尾新增一個元素
    clear() 	刪除列表中的所有元素
    copy() 	返回列表的副本
    count() 	返回具有指定值的元素數量。
    extend() 	將列表元素(或任何可迭代的元素)新增到當前列表的末尾
    index() 	返回具有指定值的第一個元素的索引
    insert() 	在指定位置新增元素
    pop() 	刪除指定位置的元素
    remove() 	刪除具有指定值的專案
    reverse() 	顛倒列表的順序
    sort() 	對列表進行排序
    
  • 20 list的三種拷貝方式

    • (1) 傳地址
      • y = x
    • (2) lst的地址改變,但是內部成員指向的地址不變
      • copy()
      • y = list(x)
    • (3) lst和其內部成員的地址都改變
      • import copy as cp
      • y = cp.deepcopy(x)
  • 21 tuple 元組

    • (1) 不可更改
    • (2) 可以轉化為列表在進行更改
    • (3) 單個元組的宣告
    x = ("apple",) # 注意逗號
    
    • (4) 多個元組可以進行合併
    tuple1 = ("a", "b" , "c")
    tuple2 = (1, 2, 3)
    tuple3 = tuple1 + tuple2
    
  • 22 set 集合

    • (1) 集合是無序的,不可以用下標讀取
    • (2) 可以for遍歷
    for x in thisSet:
        print(x)
    
    • (3) set.add(value)
    • (4) set.update(set)
    thisset = {"apple", "banana", "cherry"}
    thisset.update({"orange", "mango", "grapes"})
    
    • (5) set.remove(value)
    • (6) set.discard(value) // 和remove作用相同
    • (6) 還可以使用 pop() 方法刪除專案
      • 但此方法將刪除最後一項。請記住,set 是無序的,因此您不會知道被刪除的是什麼專案。
      • pop() 方法的返回值是被刪除的專案。
    • (7) set.clear()
    • (8) 合併兩個集合
    set1 = {"a", "b" , "c"}
    set2 = {1, 2, 3}
    set3 = set1.union(set2) # union() 和 update() 都將排除任何重複項。
    
    • (9) set 的內建方法
    add() 	向集合新增元素。
    clear() 	刪除集合中的所有元素。
    copy() 	返回集合的副本。
    difference() 	返回包含兩個或更多集合之間差異的集合。
    difference_update() 	刪除此集合中也包含在另一個指定集合中的專案。
    discard() 	刪除指定專案。
    intersection() 	返回為兩個其他集合的交集的集合。
    intersection_update() 	刪除此集合中不存在於其他指定集合中的專案。
    isdisjoint() 	返回兩個集合是否有交集。
    issubset() 	返回另一個集合是否包含此集合。
    issuperset() 	返回此集合是否包含另一個集合。
    pop() 	從集合中刪除一個元素。
    remove() 	刪除指定元素。
    symmetric_difference() 	返回具有兩組集合的對稱差集的集合。
    symmetric_difference_update() 	插入此集合和另一個集合的對稱差集。
    union() 	返回包含集合並集的集合。
    update() 	用此集合和其他集合的並集來更新集合。
    
  • 23 dict python字典

    • (1) thisdict = {“brand”: “Porsche”,“model”: “911”,“year”: 1963}
    • (2) 通過“鍵-值”獲取value
      • x = thisdict[“model”]
      • x = thisdict.get(“model”)
    • (3) 鍵值對的讀取
      • thisdict.values()
      • thisdict.keys()
      • thisdict.items()
    • (4) 新增鍵值對
      • thisdict[“color”] = “red”
    • (5) 刪除專案
      • thisdict.pop(“model”)
      • popitem() 方法刪除最後插入的專案:thisdict.popitem()
      • del thisdict[“model”]
    • (6) 拷貝
      • dict2 = thisdict
      • dict2 = thisdict.copy()
      • dict2 = dict(thisdict)
    • (7) dict 內建方法
    clear() 	刪除字典中的所有元素
    copy() 	返回字典的副本
    fromkeys() 	返回擁有指定鍵和值的字典
    get() 	返回指定鍵的值
    items() 	返回包含每個鍵值對的元組的列表
    keys() 	返回包含字典鍵的列表
    pop() 	刪除擁有指定鍵的元素
    popitem() 	刪除最後插入的鍵值對
    setdefault() 	返回指定鍵的值。如果該鍵不存在,則插入具有指定值的鍵。
    update() 	使用指定的鍵值對字典進行更新
    values() 	返回字典中所有值的列表
    
  • 24 if-elif-else

    • (1)
    a = 200
    b = 66
    if b > a:
    print("b is greater than a")
    elif a == b:
    print("a and b are equal")
    else:
    print("a is greater than b")
    
    • (2) 單行if-else語句
    • print(“A”) if a > b else print(“B”)
  • 25 while-else 迴圈

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")
  • 26 for 迴圈

    • (1)
    for x in "banana":
        print(x)
    
    • (2)
    for x in range(3, 50, 6):
        print(x)
    
    • (3) for-else
    for x in range(10):
        print(x)
    else:
        print("Finally finished!")
    
    • (4) for 語句不能為空,但如果處於某種原因寫了無內容的 for 語句,則使用 pass 語句來避免錯誤。
    for x in [0, 1, 2]:
        pass
    
  • 27 python 函式

def my_function():
  print("Hello from a function")
- (1) return
```
def my_function(x):
    return 5 * x
```
- (2) key = value 語法傳送引數。
```
def my_function(child3, child2, child1):
    print("The youngest child is " + child3)
my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")
```
- (3) 任意引數:如果不知道將傳遞給您的函式多少個引數,則在函式定義的引數名稱前新增 *。
    這樣,函式將接收一個引數元組,並可以相應地訪問各項.
```
def my_function(*kids):
    print("The youngest child is " + kids[2])
my_function("Phoebe", "Jennifer", "Rory")
```
  • 28 lambda 函式
lambda arguments : expression
- (1) 把作為引數傳入的數字加 10,然後列印結果
```
x = lambda a : a + 10
print(x(5))
```
- (2) lambda 函式可接受任意數量的引數
```
x = lambda a, b : a * b
```
- (3) 一個帶一個引數的函式定義,並且該引數將乘以未知數字
```
def myfunc(n):
    return lambda a : a * n
mydoubler = myfunc(2) # 這裡myfunc(2) 就是2a
print(mydoubler(11))
```
- (4) 在同一程式中使用相同的函式定義來生成兩個函式
```
def myfunc(n):
    return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11)) 
print(mytripler(11))
```
  • 29 global關鍵字

    • global 關鍵字使變數成為全域性變數。
  • 30 python模組

mymodule.py檔案內容:
def func(name):
	print(name)
person={"name": "Bill","age": 63,"country": "USA"}
---

import mymodule as m
m.func(“hello world”)
for i in m.person:
print(i)

---

匯入部分
from mymodule import person
person[“age”]


- 31 顯示時間

import datetime
x = datetime.datetime.now()
print(x)
x.strftime("%A") # ‘Thursday’
x.year

    - (1) 建立日期物件
    ```
    import datetime
    x = datetime.datetime(2015,2,2,1,1,1)
    print(x) # 2015-02-02 01:01:01
    ```
    - (2) strftime()函式
    ![strftime函式](strftime函式.png)

- 32 顯示已經安裝的所有package
    - pip list

- 33 try-except-else-finally

try:
print(x)
except:
print(“Something went wrong”)
else:
print(“this is else area”)
finally:
print(“The ‘try except’ is finished”)


- 34 raise語句

x = -1
if x<0:
raise Exception(“Number must greater than 0”)


- 35 字串格式化
    - (1) 格式佔位符
    ```
    price = 52
    txt = "The price is {} dollars"
    ```
    - (2) 格式化數字
    ```
    txt = "The price is {:.2f} dollars"
    ```
    - (3) 索引號(可是多次使用同一索引號)
    ```
    quantity = 3
    itemno = 567
    price = 52
    myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
    print(myorder.format(quantity, itemno, price))
    ```
    - (4) 命名索引
    ```
    myorder = "I have a {carname}, it is a {model}."
    print(myorder.format(carname = "Porsche", model = "911"))
    ```

## python類

- 1 __init__(self)建構函式

- 2 一般函式

class Person:
def init(self, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(self):
print("Hello my name is " + self.name)


- 3 self的改名

class Person:
def init(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)


- 4 刪除物件的屬性

del p1.age


- 5 繼承

class Person:
def init(self,fname,lname):
self.fname = fname
self.lname = lname

class Student(Person):
def init(self, fname, lname, year):
Person.init(self,fname, lname)
self.graduationyear = year

x = Student(“Elon”, “Musk”, 2019)


- 6 迭代器
    - (1) 可迭代物件:列表、元組、字典、集合和字串
    - (2) 迭代方法:iter和next
    ```
    mytuple = ("apple", "banana", "cherry")
    myit = iter(mytuple)

    print(next(myit))
    print(next(myit))
    print(next(myit))
    ```
    - (3) for 迴圈實際上建立了一個迭代器物件,併為每個迴圈執行 next() 方法。
    - (4) 建立迭代器
        - 要把物件/類建立為迭代器,必須為物件實現 __iter__() 和 __next__() 方法。
        - __iter__() 方法的作用相似,您可以執行操作(初始化等),但必須始終返回迭代器物件本身。
        - __next__() 方法也允許您執行操作,並且必須返回序列中的下一個專案。
        ```
        class MyNumbers:
            def __iter__(self):
                self.a = 1
                return self
            def __next__(self):
                x = self.a
                self.a += 1
                return x
        myclass = MyNumbers()
        myiter = iter(myclass)

        print(next(myiter))
        print(next(myiter))
        print(next(myiter))
        print(next(myiter))
        print(next(myiter))
        ```
    - (5) 在 __next__() 方法中,如果迭代完成指定的次數,我們可以新增一個終止條件來引發錯誤
        - 為了防止迭代永遠進行,我們可以使用 StopIteration 語句。
        ```
        class MyNumbers:
            def __iter__(self):
                self.a = 1
                return self

            def __next__(self):
                if self.a <= 20:
                    x = self.a
                    self.a += 1
                    return x
                else:
                    raise StopIteration
        myclass = MyNumbers()
        myiter = iter(myclass)
        for x in myiter:
            print(x)
        ```

## JSON

- 1 定義
    - JSON 是用於儲存和交換資料的語法。
    - JSON 是用 JavaScript 物件表示法(JavaScript object notation)編寫的文字。

- 2 import json

- 3 json字串: '{ "name":"Bill", "age":63, "city":"Seatle"}'
    - (1) json.loads()函式:json字串→字典
    ```
    import json
    x = '{ "name":"Bill", "age":63, "city":"Seatle"}'
    y = json.loads(x)
    print(y)
    # {'name': 'Bill', 'age': 63, 'city': 'Seatle'}
    ```
    - (2) json.dumps()函式:python字典→json字串
    - (3) 以下python物件可以轉化為json字串
    ```
    dict list tuple  string  int float True False None
    print(json.dumps({"name": "Bill", "age": 63}))
    print(json.dumps(["apple", "bananas"]))
    print(json.dumps(("apple", "bananas")))
    print(json.dumps("hello"))
    print(json.dumps(42))
    print(json.dumps(31.76))
    print(json.dumps(True))
    print(json.dumps(False))
    print(json.dumps(None))
    ```

- 4 json.dumps(x,indent=4) 實現轉化為json字串的縮排

import json

x = {
“name”: “Bill”,
“age”: 63,
“married”: True,
“divorced”: False,
“children”: (“Jennifer”,“Rory”,“Phoebe”),
“pets”: None,
“cars”: [
{“model”: “Porsche”, “mpg”: 38.2},
{“model”: “BMW M5”, “mpg”: 26.9}
]
}

print(json.dumps(x,indent=4))


- 5 改寫分隔符
    - 預設為:(", ", ": ")
    - 改寫為:json.dumps(x, indent=4, separators=(". ", " = "))

import json
x = {
“name”: “Bill”,
“age”: 63,
“married”: True,
“divorced”: False,
“children”: (“Jennifer”,“Rory”,“Phoebe”),
“pets”: None,
“cars”: [
{“model”: “Porsche”, “mpg”: 38.2},
{“model”: “BMW M5”, “mpg”: 26.9}
]
}
print(json.dumps(x, indent=4, separators=(". ", " = ")))


- 6 對結果進行排序
    - json.dumps(x, indent=4, sort_keys=True)

## regex 正則表示式

- 1 import re
    - 以china開頭,以country結尾:x = re.search("^China.*country$", txt)
    - findall 	返回包含所有匹配項的列表
    - search 	如果字串中的任意位置存在匹配,則返回 Match 物件
    - split 	返回在每次匹配時拆分字串的列表
    - sub 	用字串替換一個或多個匹配項

- 2 正則表示式語法
---
![正則表示式語法1](正則表示式.png)
![正則表示式語法2](正則表示式特殊序列.png)
![正則表示式語法3](正則表示式集合.png)

- 3 findall() 函式

- 4 search() 函式
    - 如果有多個匹配,則僅返回首個匹配項

import re
str = “China is a great country”
x = re.search("\s", str)
print(x) #<re.Match object; span=(5, 6), match=’ '>

    - 返回的是Match物件
        - span()
        - string
        - group()

- 5 split() 函式
    - x = re.split(regex, str, int) // int 表示分割的次數

- 6 sub() 函式
    - x = re.sub("\s", "9", str, 2) // 2 是替換次數