根据url链接下载word文档(doc、docx)、excel(xlsx、xls)、pdf、txt,并解析获取其中的内容(段落、表格)形式

目录

主函数的逻辑代码如下

根据url下载文件的函数如下

 解析txt,返回txt文件内容

解析word文档,返回内容

解析excel,返回excel内容

解析pdf,返回pdf内容


主函数的逻辑代码如下

def main(link):
    if not os.path.isdir('./yuxi'):
        os.mkdir('./yuxi')
    files_path = './yuxi'
    rename_title = hashlib.md5(title.encode('utf-8'))
    title_md5 = rename_title.hexdigest()
    the_path = os.path.join(files_path, title_md5)
    if 'zip' in link or 'rar' in link:
        with open('yuxi.txt', 'a', encoding='utf-8') as file_txt:
            file_txt.write(url)
        continue
    if '.docx' in link:
        the_path = f'{the_path}.docx'
    elif '.doc' in link:
        the_path = f'{the_path}.doc'
    elif 'xlsx' in link:
        the_path = f'{the_path}.xlsx'
    elif 'xls' in link:
        the_path = f'{the_path}.xls'
    elif 'txt' in link:
        the_path = f'{the_path}.txt'
    else:
        the_path = f'{the_path}.pdf'
    state = download_file(link, the_path)
    if state:
        if '.docx' in link:
            new_content = convert_doc_to_txt(files_path, the_path, 'docx')
        elif '.doc' in link:
            new_content = convert_doc_to_txt(files_path, the_path, 'doc')
        elif 'xlsx' in link:
            new_content = convert_xlsx_to_txt(the_path)
        elif 'xls' in link:
            new_content = read_xls(the_path)
        elif 'txt' in link:
            new_content = read_txt(the_path)
        else:
            new_content = convert_pdf_to_txt(the_path)
    else:
        new_content = None
    if new_content:
        new_content = new_content.strip()
    if not new_content:
        new_content = None
    if not re.search(r'[\u4e00-\u9fa5]', new_content):
        new_content = None


if __name__ == '__main__':
    url = 'xxxxxxxxxx'
    main(url)

根据url下载文件的函数如下

def download_file(link, the_path):
    """下载文件."""
    try:
        response = req.get(link, stream=True, timeout=500)
        chunk_size = 1024
        with open(the_path, "wb") as file:
            for data in response.iter_content(chunk_size=chunk_size):
                file.write(data)
                # count += len(data)
            return True
    except req.RequestException:
        print(f'下载文件失败')
        return False

 解析txt,返回txt文件内容

def read_txt(the_path):
    """txt文本解析."""
    with open(the_path, "rb") as file:
        txt = str(file.read())
    return txt

解析word文档,返回内容

def convert_doc_to_txt(p_path, pat, the_type):
    """解析doc文件."""
    txt = ""
    new_path = f"{pat}"
    if the_type == 'doc':
        # doc文件转为docx文件
        subprocess.run(
            ["/bin/libreoffice", "--headless", "--convert-to", "docx", "--outdir", p_path, pat],
            shell=False,
            check=True,
            encoding="utf-8",
        )
        new_path = f"{pat}x"
    # 直接读取docx文件
    try:
        file = docx.Document(new_path)
        # 段落
        for ele_p in file.paragraphs:
            txt += ele_p.text
        # 表格
        for table in file.tables:
            for row in table.rows:
                for cell in row.cells:
                    txt += cell.text
    except Exception as exception:
        print(f"ERROR !!! {exception}")
    # 读取完后删除docx文件
    os.remove(f"{pat}")
    return txt

解析excel,返回excel内容

def convert_xlsx_to_txt(file_name):
    """read excel."""
    wb = load_workbook(file_name)
    sheets = wb.get_sheet_names()
    # 第一个表格的名称
    sheet_first = sheets[0]
    # 获取特定的worksheet
    ws = wb.get_sheet_by_name(sheet_first)
    # 获取表格所有行和列,两者都是可迭代的
    rows = ws.rows
    # 迭代所有的行
    txt = ''
    for row in rows:
        txt_0 = ''
        for col in row:
            if col.value:
                txt_0 += str(col.value)
        txt += txt_0
    return txt


def read_xls(excel_name):
    """读取xls"""
    workbook = open_workbook(excel_name)

    sheet_name = workbook.sheet_names()
    sheet = workbook.sheet_by_name(sheet_name[0])

    rows = sheet.get_rows()
    txt = ''
    for row in rows:
        txt_0 = ''
        for col in row:
            if col.value:
                txt_0 += str(col.value)
        txt += txt_0
    return txt

解析pdf,返回pdf内容

def convert_pdf_to_txt(pdf_path):
    """pdf文本解析."""
    with pdfplumber.open(pdf_path) as pdf:
        content = ''
        try:
            for i in range(len(pdf.pages)):
                page = pdf.pages[i]
                page_content = '\n'.join(page.extract_text().split('\n')[:-1])
                content = content + page_content
        except Exception as exception:
            print(f"ERROR !!! {exception}")
    pdf.close()
    return content
### 支持多格式文件预览的插件 对于Web应用程序而言,支持多种文档格式(如 PDFDOCDOCXXLSXXLSTXT)在线预览的需求可以通过集成特定的JavaScript库或服务来实现。以下是几种常见的解决方案: #### 使用Mammoth.js处理Word文档 为了使浏览器端可以解析展示 `.doc` 或者 `.docx` 文件的内容,可以选择使用 Mammoth.js 这样的工具。它允许开发者轻松地将 Word 文档转换为 HTML 格式以便于网页显示。 ```javascript const mammoth = require("mammoth"); async function convertDocxToHtml(fileBuffer) { const result = await mammoth.convertToHtml({ buffer: fileBuffer }); console.log(result.value); // The generated HTML } ``` 此方法适用于简单的文字和样式保留较好的场景[^1]。 #### 利用SheetJS读取Excel表格数据 当涉及到 Excel 表格文件 (`.xls`, `.xlsx`) 的时候,推荐采用 SheetJS 库来进行操作。通过它可以方便地加载工作簿对象将其中的数据渲染到页面上作为表格形式呈现给用户查看。 ```javascript import * as XLSX from 'xlsx'; function loadSpreadsheet(fileInput){ var reader = new FileReader(); reader.onload = function(e) { var data = new Uint8Array(e.target.result); /* read workbook */ var wb = XLSX.read(data, {type:'array'}); /* grab first sheet */ var wsname = wb.SheetNames[0]; var ws = wb.Sheets[wsname]; /* generate CSV and HTML */ var csv = XLSX.utils.sheet_to_csv(ws,{FS:"\t"}); document.getElementById('output').innerHTML = "<pre>" + csv + "</pre>"; }; reader.readAsArrayBuffer(fileInput.files[0]); } ``` 这种方法能很好地兼容不同版本的 Excel 文件,提供灵活的数据提取方式。 #### 集成PDF.js用于PDF阅读器功能 针对 PDF 文件,则可以直接利用 Mozilla 开发维护的开源项目——PDF.js 来构建内嵌式的 PDF 查看组件。该方案不仅跨平台而且性能优越,在大多数现代浏览器中都能良好运行。 ```html <iframe src="https://mozilla.github.io/pdf.js/web/viewer.html?file=your-pdf-file.pdf"></iframe> ``` 上述 iframe 方案简单易行;如果追求更紧密的集成效果还可以考虑直接引入官方提供的 JavaScript API 实现自定义界面布局。 #### 对于纯文本文件(TXT) 最简易的方式莫过于创建一个 `<textarea>` 输入框或是设置 `contenteditable=true` 属性的文字区域用来承载 .txt 文件中的内容了。当然也可以先经过服务器端脚本做初步清理再传回前端展现更为整洁美观的结果。 综上所述,结合以上提到的技术栈完全可以满足对各类常见办公软件所产生物料进行高效便捷浏览的要求。值得注意的是实际开发过程中可能还需要额外关注安全性验证以及用户体验优化等方面的工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值