【问题标题】:Is there any way to open all types of files (.txt, .doc, .ppt, .xlsx etc) in python有什么方法可以在 python 中打开所有类型的文件(.txt、.doc、.ppt、.xlsx 等)
【发布时间】:2017-04-24 13:14:46
【问题描述】:

我可以通过此代码打开任何 .txt 文件

userinput1  = input ("Enter file name:")
myfile1 = open(userinput1).read()
print(myfile1)

但是当我打开任何 pdf 或 ppt 或 xlsx 文件时,它会给出错误。任何人都可以帮助我或告诉我任何方法可以在 python 中打开所有类型的文件(.txt、.doc、.ppt、.xlsx 等)

输出:

输出:

Traceback (most recent call last):
  File "C:/Users/umer/Desktop/stack.py", line 33, in <module>
    myfile1 = open(userinput1).read()
  File "C:\Python34\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 370: character maps to <undefined>

【问题讨论】:

  • @Stefan Pochmann 输出:回溯(最后一次调用):文件“C:/Users/umer/Desktop/stack.py”,第 33 行,在 myfile1 = open(userinput1) .read() 文件“C:\Python34\lib\encodings\cp1252.py”,第 23 行,解码返回 codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't解码位置 370 中的字节 0x81:字符映射到
  • 您需要为您列出的每种类型使用不同的库。它们都是二进制格式,包含以非常不同的方式存储的各种信息(例如,PDF 可以包含图像、音频甚至视频;xlsx 可能包含图表)。这在很大程度上取决于您实际想要对这些信息做什么,但很可能您需要为每种文件类型使用单独的方法。
  • 当然你可以用二进制模式读取它们:open(userinput1, 'rb').read(),但这只会返回一个二进制数据块,这在大多数情况下是没有用的。
  • 那么如何将该二进制代码转换为文本? @lenz
  • 那么您需要为您需要处理的每种文件类型使用适当的库(如@lenz 所写),而您接受的答案实际上对您毫无用处。另请注意,从 PDF 中可靠地提取文本是极其困难的;这是一种令人惊讶的低级格式。你得到一个字母流和它们的位置,提取器必须猜测(并不总是正确)单词的边界在哪里。

标签: python nlp nltk


【解决方案1】:

对此没有统一的答案,因为每个文件都有自己的编码,所以对于读写,你需要知道使用哪种编码。

例如,您可以使用

import codecs
userinput1  = input ("Enter file name:")
myfile1 = codecs.open(userinput1, "r", "latin-1").read()
print(myfile1)

但您仍然需要知道文件的编码并相应地进行更改(在本例中为latin-1)。

【讨论】:

  • 什么是pdf文件的编码或如何知道文件的编码? @Stefan pochmann
  • 问题不仅仅是编码:它是关于访问(文本?)包含在二进制格式中的信息。这与仅指定文本文件的输入编码不同。
  • import codecs userinput1 = input ("Enter file name:") myfile1 = codecs.open(userinput1, "r", "latin-1").read() print(myfile1) by this code我打开了 pdf 文件,但它显示了这样的符号“9Ud5cDcTGÓfÔ。如何将其转换为文本格式并显示@lenz
猜你喜欢
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
  • 2018-07-13
  • 2015-11-11
  • 2021-06-30
  • 1970-01-01
相关资源
最近更新 更多