无法安装textract/antiword时,如何在PythonAnywhere的Django API(Python2.7)中提取.doc文本?
Got it, let's tackle this problem. Since you can't use textract or antiword on PythonAnywhere, we need a pure-Python approach or leverage tools that are likely already available (or can be installed without extra hassle) on their Linux environment. Here are two solid solutions:
olefile .doc files are OLE compound documents, and olefile is a pure-Python library that can parse these files to extract raw text content. It doesn't require any system-level dependencies, so it's ideal for PythonAnywhere.
Steps to implement:
First, install the library via pip (run this in PythonAnywhere's console):
pip install olefileAdd a
.docextraction function to your existing code:import olefile import docx import os def extract_doc_text(filename): try: with olefile.OleFileIO(filename) as ole: # Most .doc files store text in the "WordDocument" stream if ole.exists("WordDocument"): stream = ole.openstream("WordDocument") raw_data = stream.read() # Convert binary data to text (handle .doc's UTF-16 encoding) text = raw_data.decode("utf-16", errors="ignore") # Clean up unreadable control characters cleaned_text = ''.join([c for c in text if ord(c) >= 32 or c in '\n\r\t']) return cleaned_text.strip() return "" except Exception as e: print(f"Error extracting .doc text: {e}") return "" def getText(filename): ext = os.path.splitext(filename)[1].lower() if ext == ".docx": doc = docx.Document(filename) fullText = [para.text for para in doc.paragraphs] return '\n'.join(fullText) elif ext == ".doc": return extract_doc_text(filename) else: return "Unsupported file format" # Usage remains unchanged data = getText(file_path)
This is a simplified extraction—for super complex .doc files with tables, nested formatting, etc., it might miss some content, but it works great for most basic use cases without any external tools.
PythonAnywhere's Linux environment often has LibreOffice available, or you can install it via their console (run sudo apt-get install libreoffice-writer if allowed). Converting .doc to .docx lets you reuse your existing python-docx code, which handles formatting and complex content much better.
Implementation code:
import subprocess import os import docx def convert_doc_to_docx(input_path): output_path = input_path.replace(".doc", ".docx") # Run LibreOffice in headless mode to convert the file cmd = [ "libreoffice", "--headless", "--convert-to", "docx", input_path, "--outdir", os.path.dirname(input_path) ] try: subprocess.run(cmd, check=True, capture_output=True) return output_path except subprocess.CalledProcessError as e: print(f"Conversion failed: {e.stderr.decode()}") return None def getText(filename): ext = os.path.splitext(filename)[1].lower() if ext == ".docx": doc = docx.Document(filename) fullText = [para.text for para in doc.paragraphs] return '\n'.join(fullText) elif ext == ".doc": docx_path = convert_doc_to_docx(filename) if docx_path and os.path.exists(docx_path): text = getText(docx_path) # Optional: Delete the converted .docx file after extraction to save space os.remove(docx_path) return text return "Failed to convert .doc file" else: return "Unsupported file format"
This method is far more reliable for complex documents, as LibreOffice's conversion engine is designed to handle all edge cases of the .doc format. Just double-check that LibreOffice is accessible on your PythonAnywhere instance.
内容的提问来源于stack exchange,提问作者qwerty

