2013-11-01 31 views
0

我可以讀取整個字符串,但它不計算各個字符。我想創建一個字符的字典,我從Python中的文本文件中讀取

以下是我有:

#!/usr/bin/python2.7 

ans = True 

while ans: 
    print(""" 
    1. Read in an text file. 

    Press enter to exit 
    """) 

    ans=raw_input("Make a selection") 

    if ans == "1": 

     print("Enter in a text file to open") 
     txt = raw_input("> ") 
     txt_open = open(txt, 'r') 

     d = dict() 
     for c in txt_open: 
      if c not in d: 
       d[c] = 1 
      else: 
       d[c] += 1 

     print d 
+0

能否請你告訴輸入的是什麼樣的,和什麼是預期的輸出? – aIKid

+0

字典是從鍵到值的映射。你不能只擁有某種價值的字典,也不能說出你想要映射的內容。 – abarnert

+0

無論如何,這聽起來像你正在嘗試構建類似['collections.Counter'](http://docs.python.org/2/library/collections.html#collections.Counter)。爲什麼不使用它? (或者,如果您想知道它是如何工作的,請查看[源文件](http://hg.python.org/cpython/file/2.7/Lib/collections.py#l387) - 這就是爲什麼文檔頁面有一個鏈接。) – abarnert

回答

2

的問題是文件的,不字符的迭代。所以,在此:

for c in txt_open: 

每個c是一個整行。如果你想在該行的每個字符,添加另一個循環:

for line in txt_open: 
    for c in line: 

或者,如果你願意,你可以read整個文件分割成一個大的字符串和環比的字符(但請記住,這意味着你需要適應整個文件到內存中,並且你需要讀取整個文件,然後纔可以處理任何的話):

for c in txt_open.read(): 

在未來,當你有這樣的問題,第一個一步應該看看你得到的價值。您可以使用調試器或實時可視化工具,也可以將print語句添加到代碼中。例如,如果你print每個c,它會立即明白什麼是錯的。


同時,你正在構建已經在STDLIB爲Counter存在,所以你可以使用它:

d = collections.Counter() 
for line in txt_open: 
    for c in line: 
     d[c] += 1 

...或者更簡單地說:

d = collections.Counter() 
for line in txt_open: 
    d.update(line) 

...或者,即使更多只需:

d = collections.Counter(c for line in txt_open for c in line) 

...或者,如果你喜歡:

d = collections.Counter(txt_open.read()) 
+0

謝謝你的幫助。額外的循環修復了我的問題。我是python的新手。我刪除了所有的打印語句和檢查,以使代碼儘可能小。猜猜我將在未來離開他們。 – will3

+0

@ will3:一旦你知道它正在工作,或者你已經從他們那裏獲得了儘可能多的信息,就可以拿出「印刷品」。 (如果你需要一些信息來幫助調試問題,請發佈你學到的東西,作爲你的SO問題的一部分,如果你說「我在'for'循環後面加了一個'print c',每個都是一堆人物,或許是一整條線「,人們會知道你已經想出了什麼,沒有什麼,並且通常可以幫助你更快地解決問題。 – abarnert

0
dict_ = collections.defaultdict(int) 

with open(filename, 'r') as file_: 
    for line in file_: 
     for character in line: 
     dict_[character] += 1 

HTH

+1

我無法想象任何情況下,你不能使用'計數器',但可以使用'defaultdict'手動嘗試建立一個'計數器'... – abarnert

0

您需要添加另一個for循環的每一行,以達到每個字符:

for line in txt_open: 
    for c in line: 
     if c not in d: 
      d[c] = 1 
     else: 
      d[c] += 1 

print d 
相關問題