Python 語音輸入與檔案

語音輸入雜湊表

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

在字典中尋找或設定值時,請使用方括號,例如 dict['foo'] 查詢鍵「foo」下的值。字串、數字和元組可做為鍵,且任何類型都可以是值。其他型別不一定能夠正確以鍵 (字串和元組) 的形式運作 (字串和元組不可變更,因此運作順暢)。尋找不在字典中的值會擲回 KeyError;使用「in」檢查鍵是否在字典中,或使用 dict.get(key) 來傳回值;如果沒有鍵,則使用 dict.get (key) 或 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」鍵的 dict

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

  ## 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}

Files

open() 函式會開啟並傳回檔案控制代碼,可用來照常讀取或寫入檔案。程式碼 f = open('name', 'r') 將檔案開啟到變數 f 中,可以開始讀取作業,並在完成時使用 f.close()。使用「w」來代替「r」,使用「a」表示附加,使用「a」表示附加。標準 for-loop 適用於文字檔,也就是在檔案的各行間疊代 (僅適用於文字檔案,不適用於二進位檔案)。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 檔案中的每一行,就可派上用場。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 摘要練習以基本練習來進行。