如果要在字符串中查找複雜模式,正則表達式非常有用。因爲你想計算(而不是尋找)簡單的(只是單個字母字符)「模式」,正則表達式不是這裏選擇的工具。
如果我正確理解你正在嘗試的是什麼,解決此問題的最透明的方法是遍歷所有行,並遍歷該行中的所有字符,如果該字符是字母,則將1添加到相應的字典條目。在代碼:
filename=raw_input()
found = {}
with open(filename) as file:
for line in file:
for character in line:
if character in "abcdefghijklmnopqrstuvxyz":
# Checking `in (explicit string)` is not quick, but transparent.
# You can use something like `character.isalpha()` if you want it to
# automatically depend on your locale.
found[character] = found.get(character, 0)+1
# If there is no dictionary entry for character yet, assume default 0
# If you need e.g. small and capital letters counted together,
# "Normalize" them to one particular type, for example using
# found[character.upper()] = found.get(character, 0)+1
經過這個循環已經通過文件運行,字典found
將包含OCCURENCES每個字符的數量。
這是功課?如果是這樣,它應該被標記爲這樣。 – 2012-03-23 19:42:41
不,我使用'python for rookies'來完成任務。但我會牢記以備將來參考。謝謝 – Unknown 2012-03-23 19:48:57
對於一個好問題+1 :-) – 2012-03-23 19:51:51