我可以讀取整個字符串,但它不計算各個字符。我想創建一個字符的字典,我從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
能否請你告訴輸入的是什麼樣的,和什麼是預期的輸出? – aIKid
字典是從鍵到值的映射。你不能只擁有某種價值的字典,也不能說出你想要映射的內容。 – abarnert
無論如何,這聽起來像你正在嘗試構建類似['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