2012-03-23 14 views
4

我遇到了一些Python工作的問題。我必須編寫一段通過CMD運行的代碼。我需要它然後打開用戶指出的文件並計算它包含的每個字母字符的數量。Python的正則表達式和CMD

到目前爲止,我有這個,我可以通過CDM運行,並指定要打開的文件。我弄亂了正則表達式,仍然無法弄清楚如何計算單個字符。有任何想法嗎?對不起,如果我解釋得很糟。

import sys 
import re 


filename = raw_input() 
count = 0 
datafile=open(filename, 'r') 
+1

這是功課?如果是這樣,它應該被標記爲這樣。 – 2012-03-23 19:42:41

+1

不,我使用'python for rookies'來完成任務。但我會牢記以備將來參考。謝謝 – Unknown 2012-03-23 19:48:57

+1

對於一個好問題+1 :-) – 2012-03-23 19:51:51

回答

1

我會遠離正則表達式。他們會變得緩慢而醜陋。相反,將整個文件讀入一個字符串,並使用內置的字符串方法count來計算字符。

要放在一起你:

filename = raw_input() 
datafile=open(filename, 'r') 
data = datafile.read() 
datafile.close() # Don't forget to close the file! 
counts = {} # make sure counts is an empty dictionary 
data = data.lower() # convert data to lowercase 
for k in range(97, 123): # letters a to z are ASCII codes 97 to 122 
    character = chr(k) # get the ASCII character from the number 
    counts[character] = data.count(character) 

然後,你必須包含所有的計數的字典counts。例如,counts['a']會爲您提供文件中的a s的編號。或者,對於整個計數列表,請執行counts.items()

+1

對於大文件,使用計數功能會抑制性能。整個數據集是爲每個被計數的字符讀取的。 – 2012-03-23 20:03:56

+1

那麼,一如既往,要做的事情實際上是衡量業績。至少在文件高達100MB時,上面的代碼運行速度至少比使用「集合」時快15倍(在我的機器上,使用python 2.7.2)。無論是對於整個腳本還是對於循環都是如此。 – Mike 2012-03-24 23:13:27

3

計數器類型對計數項目很有用。它是在Python 2.7增加:

import collections 
counts = collections.Counter() 
for line in datafile: 
    # remove the EOL and iterate over each character 
    #if you desire the counts to be case insensitive, replace line.rstrip() with line.rstrip().lower() 
    for c in line.rstrip(): 
     # Missing items default to 0, so there is no special code for new characters 
     counts[c] += 1 

要查看結果:

results = [(key, value) for key, value in counts.items() if key.isalpha()] 
print results 
+0

@TimLesher文件大小如何發揮作用? – 2012-03-23 19:58:52

+1

我不認爲你想用枚舉:枚舉給你一個(n,k)序列,而不是(k,v)的序列。 – 2012-03-23 20:02:58

+0

我打算建議一個單一的閱讀和沒有循環;那麼我意識到這將是一個新的答案更清晰。 – 2012-03-23 20:03:35

1

如果你想使用正則表達式,你可以做如下:

pattern = re.compile('[^a-zA-Z]+') # pattern for everything but letters 
only_letters = pattern.sub(text, '') # delete everything else 
count = len(only_letters) # total number of letters 

用於計算不同字符的數量,使用計數器已經建議。

1

如果要在字符串中查找複雜模式,正則表達式非常有用。因爲你想計算(而不是尋找)簡單的(只是單個字母字符)「模式」,正則表達式不是這裏選擇的工具。

如果我正確理解你正在嘗試的是什麼,解決此問題的最透明的方法是遍歷所有行,並遍歷該行中的所有字符,如果該字符是字母,則將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每個字符的數量。

+0

字符串函數isalpha()與lower()結合使用比輸入「abcdefghijklmnopqrstuvxyz」更簡單 – 2012-03-23 19:46:20

2

如果該文件是足夠小,可以一次讀取所有的,它很容易的確:

from collections import Counter 

filename = raw_input() 
with open(filename) as f: 
    data = f.read() 
counter = Counter(data.lower()) 

print('\n'.join(str((ch, counter[ch])) for ch in counter if ch.isalpha())) 
+1

這比counter @ KevinCoffey's更好地使用Counter類。 – 2012-03-23 20:56:11