Thì bạn post hết code lên đây, hàm đó đúng rồi thì lúc gọi hàm đó bạn truyền biến nào vào?
Bạn tập thói quen khi hỏi cung cấp càng nhiều thông tin càng tốt, để người khác còn hiểu
Lỗi TypeError khi đọc ghi file
1 Like
sorry, đây là code, nó báo lỗi dòng infile = open(a_string, ‘r’),và dung sort() nó cũng ko xếp theo thứ tự.
def word_count(a_string):
infile = open(a_string,"r")
outfile = open("frequency.txt","w")
new_file = infile.read().split()#split the word to count
string_dict = {}#create an emty dictionary to store value
for word in new_file:
string_dict[word] = 0#begin count a word from 0
for word in new_file:
if word in string_dict.keys():
string_dict[word]=string_dict[word]+1#plus 1 if word the same
for key, value in string_dict.items():#take each item in the dictionary
outfile.write(str(key)+" "+str(value)+'\n')#write in outfile(key value and jump to another line)
#close the input and output file
outfile.close()
infile.close()
#function to print nicely
def nice_printing(a_file):
infile = open(a_file, 'r')
data = infile.read()
items = data[1:-2].split(', ')#erase the {}
items=items.sort()
for item in items:
key = item.split(',')[0][1:-1]
value = item.split(',')[1]
print(key, value)
infile.close()
name_file = raw_input("Enter the name of your text file: ")
print "Processing ...Done!"
print "Results were written to frequency.txt."
a_file=word_count(name_file)
a_new_file=nice_printing(a_file)
- Code của bạn indent lỗi. Phải thống nhất cách indent, cùng là 2 ký tự, cùng 4 ký tự hoặc cùng 8 ký tự.
- Hàm
nice_printing
bạn copy paste của mình mà không hiểu là nó dùng cho 1 bài tập khác, khi dữ liệu cần xử lý là 1 chuỗi dạng dict, vd{'a':1, 'b':2}
Còn dữ liệu cần xử lý của bạn đã nằm gọn trong hàmword_count
rồi. Trong hàm đó đã có dòng ghi ra file rồi mà.
Khi viết
a_file=word_count(name_file)
a_new_file=nice_printing(a_file)
bạn phải hiểu hàm word_count
trả về giá trị gì mà gán vào biến a_file. Ở đây nó chẳng trả về giá trị gì, mà nó thực hiện công việc đọc và ghi trong hàm đó luôn rồi. Bạn có thể print(a_file)
xem nó ra cái gì nhé.
print(a_file)
#Kết quả: None
Vì hàm word_count không trả về giá trị gì nên a_file
là None
, nên khi truyền a_file
vào nice_printing
sẽ báo lỗi.
Code như này là đủ:
def word_count(a_string):
infile = open(a_string,"r")
outfile = open("frequency.txt","w")
new_file = infile.read().split()#split the word to count
string_dict = {}#create an emty dictionary to store value
for word in new_file:
string_dict[word] = 0#begin count a word from 0
for word in new_file:
if word in string_dict.keys():
string_dict[word]=string_dict[word]+1#plus 1 if word the same
for key, value in string_dict.items():#take each item in the dictionary
outfile.write(str(key)+" "+str(value)+'\n')#write in outfile(key value and jump to another line)
#close the input and output file
outfile.close()
infile.close()
word_count('text.txt')
1 Like