谁能告诉我我的代码有什么问题?
def count_letters(in_file, out_file):
in_file = open("in_file.txt", "r")
for line in in_file:
for x in sorted(line):
count = x.count()
out_file = open("out_file.txt", "w")
print(x, " ", count)
in_file.close()
out_file.close()
print(out_file)
它应该
当我运行它时,它告诉我" in_file"没有定义,但我已经定义了它,并制作了一个" in_file.txt。"
任何帮助将不胜感激!
答案 0 :(得分:1)
你想传递" in_file.txt"作为in_file变量并使用它:
in_f=open(in_file,"r")
同样对于out_file,否则,制作函数有什么意义?
但我认为你的错误与没有" in_file.txt"在当前的工作目录中,您可以查看
import os
print os.getcwd()
这将显示代码可以看到的文件
答案 1 :(得分:0)
in_file = open(in_file, "r") # you must do the way so got an error
尝试此功能:
def count_letters(in_file, out_file):
in_file_fd = open(in_file, "r") # open in file
out_file_fd = open(out_file, "w") # open out file
for line in in_file_fd:
for x in sorted(line):
count = line.count(x)
res = x + " " + str(count) + '\n'
print (res)
out_file_fd.write(res) # write the data into out file
in_file_fd.close() # close in_file
out_file_fd.close() # close out_file
count_letters('test.py', 'out_file')
它对我有用,希望对你有所帮助。