我创建了一个简单的程序,它读取一个文件并要求用户输入一个单词,然后告诉该单词被使用了多少次。我想改进它,这样您就不必每次都输入确切的目录。我导入了 Tkinter 并使用了代码 fileName= filedialog.askfilename() 以便弹出一个框让我选择文件。每次我尝试使用它时,都会收到以下错误代码...
Traceback (most recent call last):
File "/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/How many? (Python).py", line 24, in <module>
for line in fileScan.read().split(): #reads a line of the file and stores
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8e in position 12: ordinal not in range(128)
我似乎没有收到此错误代码的唯一一次是当我尝试打开 .txt 文件时。但我也想打开 .docx 文件。提前感谢您的帮助:)
# Name: Ashley Stallings
# Program decription: Asks user to input a word to search for in a specified
# file and then tells how many times it's used.
from tkinter import filedialog
print ("Hello! Welcome to the 'How Many' program.")
fileName= filedialog.askopenfilename() #Gets file name
cont = "Yes"
while cont == "Yes":
word=input("Please enter the word you would like to scan for. ") #Asks for word
capitalized= word.capitalize()
lowercase= word.lower()
accumulator = 0
print ("\n")
print ("\n") #making it pretty
print ("Searching...")
fileScan= open(fileName, 'r') #Opens file
for line in fileScan.read().split(): #reads a line of the file and stores
line=line.rstrip("\n")
if line == capitalized or line == lowercase:
accumulator += 1
fileScan.close
print ("The word", word, "is in the file", accumulator, "times.")
cont = input ('Type "Yes" to check for another word or \
"No" to quit. ') #deciding next step
cont = cont.capitalize()
if cont != "No" and cont != "Yes":
print ("Invalid input!")
print ("\n")
print ("Thanks for using How Many!") #ending
PS 不确定是否重要,但我正在运行 OSx