我创建了一个简单的程序,它读取文件并要求用户输入一个单词,然后告诉用户该单词被使用了多少次。我想改进它,这样您就不必每次都输入确切的目录。我导入了 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
附注不确定这是否重要,但我正在运行 OSx
最佳答案
The only time I don't seem to get this error code is when I try to open a .txt file. But I'm wanting to open .docx files also.
docx
文件不仅仅是一个文本文件;它也是一个文件。这是一个Office Open XML文件:包含 XML 文档和任何其他支持文件的 zip 文件。尝试将其作为文本文件读取是行不通的。
例如,文件的前 4 个字节如下:
b'PK\x03\x04`
您无法将其解释为 UTF-8、ASCII 或其他任何内容而不得到一堆垃圾。你肯定不会在其中找到自己的话。
您可以自己进行一些处理 - 使用 zipfile
访问存档内的 document.xml
,然后使用 XML 解析器获取文本节点,然后然后重新连接它们,以便您可以在空白处拆分它们。例如:
import itertools
import zipfile
import xml.etree.ElementTree as ET
with zipfile.ZipFile('foo.docx') as z:
document = z.open('word/document.xml')
tree = ET.parse(document)
textnodes = tree.findall('.//{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t')
text = itertools.chain.from_iterable(node.text.split() for node in textnodes)
for word in text:
# ...
当然,最好实际解析 xmlns
声明并正确注册 w
命名空间,这样您就可以使用 'w:t'
,但如果您知道这意味着什么,那么您就已经知道了,如果您不知道,这里就不是介绍 XML 命名空间和 ElementTree
的教程的地方。
那么,您怎么知道它是一个充满内容的 zip 文件,并且实际文本位于文件 word/document.xml
中,而该文件中的实际文本位于.//w:t
节点,命名空间 w
映射到 http://schemas.openxmlformats.org/wordprocessingml/2006/main
, 等等?好吧,如果您对这些东西已经足够了解,您可以阅读所有相关文档并使用一些示例文件和一些探索来指导您解决问题。但如果您不这样做,您将面临一个重大的学习曲线。
即使您确实知道自己在做什么,search PyPI for a docx parser module 可能是一个更好的主意。然后就用它。
关于python - 尝试使用 Tkinter (Python) 时出现 Unicode 解码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17662249/