1. 程式人生 > 實用技巧 >【python問題合集】

【python問題合集】

python

  1. 函式引數的用法

    • *args :不確定性的列表引數
    • *kwargs:不確定性的字典引數
    • 其他引數基本與其他語言理解一致
  2. argparse模組----------命令列解析模組

    • 使用方法,在命令列中執行某python檔案即可

      python xxx.py 引數(具體怎麼寫參看說明)
      
    • 如何編寫parse模組

      引數模組如何新增,先初始化一個ArgumentParser例項,然後呼叫該類的成員函式 add_argument增加引數,具體的help

      import argparse
      
      parser = argparse.ArgumentParser(description='Process some integers.')
      parser.add_argument('integers', metavar='N', type=int, nargs='+',
                          help='an integer for the accumulator')
      parser.add_argument('--sum', dest='accumulate', action='store_const',
                          const=sum, default=max,
                          help='sum the integers (default: find the max)')
      
      args = parser.parse_args()
      print(args.accumulate(args.integers))
      
    • 測試該模組的方法

      • terminal中cd到該py檔案所在的目錄

      • 執行以下命令

      • python parselearn.py --sum  1 5 23
        
      • 注意:不要輸入一個列表 [1,2,5,6],會報錯

  3. 影象檔案讀寫顯示

    • 一張圖片上顯示多幅影象,一般有兩種方法,推薦第一種

      • import matplotlib.pyplot as plt
        plt.figure()
        plt.subplot(abc)
        plt.imshow('xxx.jpg')
        plt.show()
        
      • import matplotlib.pyplot as plt
        plt.figure()
        ax = fig.add_subplot(abc)
        ax.imshow('xxx.jpg')
        plt.show()
        
    • 影象儲存與重新讀入

      方法很多,展示一種

      • import numpy as np
        from PIL import Image
        import matplotlib.pyplot as plt
        
        
        def pic_show(img):
            plt.figure()
            plt.imshow(img)
            plt.show()
        
        
        img = Image.open('../example.jpg')
        i = 5
        data = np.save('../exe{}'.format(i), img)
        show_data = np.load('../exe{}.npy'.format(i))
        pic_show(show_data)
        
        
      • 主要用到的包就是matplotlib.pyplotPIL,至於轉換成陣列之後就numpy就好了。

      • 參看

  4. python中的tqdm

  5. python讀入json報錯TypeError:the Json object must be str, bytes or bytearray,not ‘TextIOWrapper’

    解決辦法:

    • load和dump是針對檔案操作的
    • loads和dumps是針對python物件和字串的
    • 所以目標找對,函式選對即可
    • 出現這個錯誤的原因是自己用了loads方法去將json檔案轉換為python物件,而正確的應該是使用load方法
  6. python讀入json報錯raise JSONDecodeError(“Extra data”, s, end),json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 104)

    file_path = 'train_set/label_data_0531.json'
    import json
    
    items = []
    file = open(file_path, 'r', encoding='utf-8')
    for line in file.readlines():
        dic = json.loads(line)
        items.append(dic)
    
    
    # with open(file_path, 'r') as load_f:
    #     load_dict = json.load(load_f)  用這個就會出現上述的第5個問題
    #     items.append(load_dict)
    #     #print(len(load_dict))
    
    print(len(items))
    
    

    參看

  7. python中的除法(python3.4往上)

    1. /是精確除法,//是向下取整除法,%是求模
    2. %求模是基於向下取整除法規則的
    3. 四捨五入取整round, 向零取整int, 向下和向上取整函式math.floor, math.ceil
    4. //和math.floor在CPython中的不同
    5. /在python 2 中是向下取整運算
    6. C中%是向零取整求模。
  1. pycharm如何設定像spyder一樣檢視變數

    • 針對每個具體的專案,找Edit Configurations
    • 選擇Show command line afterwards,沒有就選Run with Python console
  2. python用pip安裝cv2的時候

    • 命令是pip install opencv-python,不要用pip install cv2
    • 使用的時候直接import cv2
  3. from ignite.engine import Engine, Events

    ImportError: No module named 'ignite.engine'

    • 同第9個問題一樣,pip install pytorch-ignite
    • 不是直接pip instll ignite
  4. python的控制檯

    • Python Console叫做Python控制檯,即Python互動模式;Terminal叫做終端,即命令列模式。
    • Python互動模式主要有兩種:CPython用>>>作為提示符,而IPython用In [序號]:作為提示符。
    • Python互動式模式可以直接輸入程式碼,然後執行,並立刻得到結果,因此Python互動模式主要是為了除錯Python程式碼用的。
    • 命令列模式與系統的CMD(命令提示符)一樣,可以執行各種系統命令。
  5. python為什麼每次建立的檔案目錄下都含 .idea/資料夾?該資料夾又是用來幹嘛的?

    • 當使用pycharm作為IDE時,會自動生成 .idea/資料夾來存放專案的配置資訊。其中包括版本控制資訊、歷史記錄等等
    • 說白了, .idea/ 與當前專案能否正常執行無關,它只是負責對程式碼的歷史變化進行一個記錄,便於回溯查詢和復原
  6. python中的目錄

    • python中的目錄根據所處的系統不同,目錄的分隔符可以是’/‘,也可以是’\‘,但是由於’\‘在python中是轉義字元,所以,路徑中的’\‘要兩個來表示

    • c:/user/work
      c:\\user\\home
      二者是等價的
      
    • 1、當前目錄:os.listdir(".") f1 = open('xugang.txt','w')
      2、父目錄:os.listdir("..") f1 = open('../xugang.txt','w')
      3、根目錄寫法一:os.listdir('/') f1 = open('/xugang.txt','w')
      4、根目錄寫法二:os.listdir('') f1 = open('\xugang.txt','w')

      5、子目錄:os.listdir('mytext') f1 = open('mytext/xugang.txt','w')

    • 碟符後面的冒號不要忘

    • windows下切換碟符c:\>d:,完成到c盤到D盤的切換

    • 參看