Python 語音輸入與檔案

語音輸入雜湊資料表

Python 高效率鍵/值雜湊資料表結構稱為「dict」。字典內容可以用大括號 { } 中的一連串鍵/值組合寫成,例如:dict = {key1:value1, key2:value2, ... }。「空白字典」只是一對空白的大括號 {}。

在字典中查詢或設定值會使用方括號,例如:dict['foo'] 查詢索引鍵「foo」下的值。字串、數字和元組可做為鍵,任何類型可以是值。其他類型的鍵不一定能正確運作 (字串和元組無法變更,因此可以保持正常執行)。查詢不在字典中的值會產生 KeyError,請使用「in」請確認鍵是否在字典中,或是使用 dict.get(key),如果鍵不存在,則傳回值或 None (或 get(key, not-found) 可讓您指定要在找不到的情況下傳回什麼值。

  ## Can build up a dict by starting with the empty dict {}
  ## and storing key/value pairs into the dict like this:
  ## dict[key] = value-for-that-key
  dict = {}
  dict['a'] = 'alpha'
  dict['g'] = 'gamma'
  dict['o'] = 'omega'

  print(dict) ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}

  print(dict['a'])     ## Simple lookup, returns 'alpha'
  dict['a'] = 6       ## Put new key/value into dict
  'a' in dict         ## True
  ## print(dict['z'])                  ## Throws KeyError
  if 'z' in dict: print(dict['z'])     ## Avoid KeyError
  print(dict.get('z'))  ## None (instead of KeyError)

含有「a」鍵的字典「o」g

根據預設,字典上的 for 迴圈會反覆查詢其金鑰。鍵會以任意順序顯示。dict.keys() 和 dict.values() 方法會傳回明確包含的鍵或值清單。此外還有一個 items() 會傳回一個 (鍵、值) 元組清單,這是檢查字典中所有鍵/值資料最有效率的方法。這些清單全都可傳遞到排序() 函式。

  ## By default, iterating over a dict iterates over its keys.
  ## Note that the keys are in a random order.
  for key in dict:
    print(key)
  ## prints a g o

  ## Exactly the same as above
  for key in dict.keys():
    print(key)

  ## Get the .keys() list:
  print(dict.keys())  ## dict_keys(['a', 'o', 'g'])

  ## Likewise, there's a .values() list of values
  print(dict.values())  ## dict_values(['alpha', 'omega', 'gamma'])

  ## Common case -- loop over the keys in sorted order,
  ## accessing each key/value
  for key in sorted(dict.keys()):
    print(key, dict[key])

  ## .items() is the dict expressed as (key, value) tuples
  print(dict.items())  ##  dict_items([('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')])

  ## This loop syntax accesses the whole dict by looping
  ## over the .items() tuple list, accessing one (key, value)
  ## pair on each iteration.
  for k, v in dict.items(): print(k, '>', v)
  ## a > alpha    o > omega     g > gamma

策略注意事項:從績效角度來看,字典是你最重視的工具之一,因此建議你在容易管理資料時輕鬆使用。例如,您可能會讀取記錄檔,其中每一行開頭都是 IP 位址,並使用 IP 位址作為鍵,將資料儲存在字典中,並用其顯示為值的行清單。讀完整個檔案後,您可以查詢任何 IP 位址,並立即看到當中的行清單。這個字典會擷取零散的資料,使資料內容一致。

語音輸入格式

% 運算子可讓您輕鬆將字典中的值替換成名稱字串:

  h = {}
  h['word'] = 'garfield'
  h['count'] = 42
  s = 'I want %(count)d copies of %(word)s' % h  # %d for int, %s for string
  # 'I want 42 copies of garfield'

  # You can also use str.format().
  s = 'I want {count:d} copies of {word}'.format(h)

Del

《del》運算子則確實刪除。在最簡單的情況下,它可以移除變數的定義,就像尚未定義該變數一樣。Del 也可用於清單元素或切片中,以便刪除清單中的某個部分,以及從字典中刪除項目。

  var = 6
  del var  # var no more!

  list = ['a', 'b', 'c', 'd']
  del list[0]     ## Delete first element
  del list[-2:]   ## Delete last two elements
  print(list)      ## ['b']

  dict = {'a':1, 'b':2, 'c':3}
  del dict['b']   ## Delete 'b' entry
  print(dict)      ## {'a':1, 'c':3}

檔案

open() 函式會開啟並傳回可照常讀取或寫入檔案的檔案控制代碼。程式碼 f = open('name', 'r') 會在變數 f 中開啟檔案,以便讀取作業,並在完成時使用 f.close()。應使用「w」,而非「r」編寫程式時,「a」。「迴圈」標準適用於文字檔案,可疊代檔案行 (僅適用於文字檔案,不適用於二進位檔案)。如要查看文字檔中的所有行, for-loop 技術提供簡單又有效率的方法:

  # Echo the contents of a text file
  f = open('foo.txt', 'rt', encoding='utf-8')
  for line in f:   ## iterates over the lines of the file
    print(line, end='')    ## end='' so print does not add an end-of-line char
                           ## since 'line' already includes the end-of-line.
  f.close()

在不耗用 10 GB 記憶體的情況下,一次閱讀一行可達到一個最佳品質,不是所有檔案一次需要在記憶體中容納全部的內容。如果在不使用 10 GB 記憶體的情況下,查看 10 GB 檔案中的每一行,就很方便。f.readlines() 方法會將整個檔案讀入記憶體,然後以行清單的形式傳回檔案內容。f.read() 方法可將整個檔案讀取為單一字串,這是一次處理所有文字的便利方法,例如稍後會介紹的規則運算式。

對寫入而言,f.write(string) 方法是將資料寫入開放式輸出檔案最簡單的方法。您也可以使用「print」並開啟「print(string, file=f)」等開啟檔案。

檔案 Unicode

如要讀取及寫入 Unicode 編碼檔案,請使用 `'t'` 模式並明確指定編碼:

with open('foo.txt', 'rt', encoding='utf-8') as f:
  for line in f:
    # here line is a *unicode* string

with open('write_test', encoding='utf-8', mode='wt') as f:
    f.write('\u20ACunicode\u20AC\n') #  €unicode€
    # AKA print('\u20ACunicode\u20AC', file=f)  ## which auto-adds end='\n'

運動增量

建構 Python 程式,不必一次撰寫全部內容。與其只識別第一個里程碑,例如:「第一個步驟是擷取字詞清單」編寫程式碼以取得該里程碑,只在該時間點輸出資料結構,然後執行 sys.exit(0) 即可,讓程式避免執行到沒有完成的部分。等到里程碑代碼正常運作後,即可處理下一個里程碑的程式碼。能夠查看特定狀態下的變數列印出來,有助您思考需要如何轉換這些變數才能達到下一個狀態。Python 利用這個模式可以非常快速,讓您可以稍加變更並執行程式來查看程式的運作方式。利用這種快速交件的方式,只需幾個簡單步驟就能建構您的計畫。

練習:wordcount.py

結合所有基本 Python 教材 (字串、清單、字典、元組、檔案),請嘗試基本練習中的 wordcount.py 摘要練習。