-1
我正在嘗試編寫python代碼來讀取文件,從內容創建字典,然後檢查重複單詞的數量。下面的代碼是關於每個步驟的註釋:將文件讀入字典以檢查重複字的數量
import string
# making a dictionary from a paragraph
def make_dict(s):
some_list = s.split()
d = dict()
for word in some_list:
d[word] = 1 + d.get(word,0)
print d
print
print
return d
#Inverse the dictionary
# swap between key and value
def invert_dict(s):
inverse = {}
d = make_dict(s)
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
print inverse
print
print
return inverse
# Reading a file and copying just plain text in other file
def make_text():
file_name = raw_input('Enter file name: ')
fn = open(file_name)
for line in fn:
line = line.translate(None,"!#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~")
line = line.lower()
some_text = open('duplicate.txt','a')
some_text.write(line)
# print some_text
some_text.close()
fn.close()
return some_text
some_file = make_text()
some_dict = invert_dict(some_file)
for key in some_dict:
print key , some_dict[key]
print
當我運行代碼時,出現以下錯誤。有人能幫助解釋我做錯了什麼,以及如何解決錯誤?
Traceback (most recent call last):
File "C:\Users\KUMAR\Desktop\Python practice\DataStructureSelectionb\string_to_dictionary.py", line 51, in <module>
some_dict = invert_dict(some_file)
File "C:\Users\KUMAR\Desktop\Python practice\DataStructureSelectionb\string_to_dictionary.py", line 22, in invert_dict
d = make_dict(s)
File "C:\Users\KUMAR\Desktop\Python practice\DataStructureSelectionb\string_to_dictionary.py", line 8, in make_dict
some_list = s.split()
AttributeError: 'file' object has no attribute 'split'