码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 整理了25个Python文本处理案例,收藏!


    Python 处理文本是一项非常常见的功能,本文整理了多种文本提取及NLP相关的案例,还是非常用心的

    文章很长,高低要忍一下,如果忍不了,那就收藏吧,总会用到的

    萝卜哥也贴心的做成了PDF,在文末获取!

    • 提取 PDF 内容
    • 提取 Word 内容
    • 提取 Web 网页内容
    • 读取 Json 数据
    • 读取 CSV 数据
    • 删除字符串中的标点符号
    • 使用 NLTK 删除停用词
    • 使用 TextBlob 更正拼写
    • 使用 NLTK 和 TextBlob 的词标记化
    • 使用 NLTK 提取句子单词或短语的词干列表
    • 使用 NLTK 进行句子或短语词形还原
    • 使用 NLTK 从文本文件中查找每个单词的频率
    • 从语料库中创建词云
    • NLTK 词法散布图
    • 使用 countvectorizer 将文本转换为数字
    • 使用 TF-IDF 创建文档术语矩阵
    • 为给定句子生成 N-gram
    • 使用带有二元组的 sklearn CountVectorize 词汇规范
    • 使用 TextBlob 提取名词短语
    • 如何计算词-词共现矩阵
    • 使用 TextBlob 进行情感分析
    • 使用 Goslate 进行语言翻译
    • 使用 TextBlob 进行语言检测和翻译
    • 使用 TextBlob 获取定义和同义词
    • 使用 TextBlob 获取反义词列表

    提取 PDF 内容

    # pip install PyPDF2  安装 PyPDF2
    import PyPDF2
    from PyPDF2 import PdfFileReader
     
    # Creating a pdf file object.
    pdf = open("test.pdf", "rb")
     
    # Creating pdf reader object.
    pdf_reader = PyPDF2.PdfFileReader(pdf)
     
    # Checking total number of pages in a pdf file.
    print("Total number of Pages:", pdf_reader.numPages)
     
    # Creating a page object.
    page = pdf_reader.getPage(200)
     
    # Extract data from a specific page number.
    print(page.extractText())
     
    # Closing the object.
    pdf.close()
    • 1

    提取 Word 内容

    # pip install python-docx  安装 python-docx


    import docx
     
     
    def main():
        try:
            doc = docx.Document('test.docx')  # Creating word reader object.
            data = ""
            fullText = []
            for para in doc.paragraphs:
                fullText.append(para.text)
                data = '\n'.join(fullText)
     
            print(data)
     
        except IOError:
            print('There was an error opening the file!')
            return
     
     
    if __name__ == '__main__':
        main()
    • 1

    提取 Web 网页内容

    # pip install bs4  安装 bs4

    from urllib.request import Request, urlopen
    from bs4 import BeautifulSoup
     
    req = Request('http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1',
                  headers={ 'User-Agent': 'Mozilla/5.0'})
     
    webpage = urlopen(req).read()
     
    # Parsing
    soup = BeautifulSoup(webpage, 'html.parser')
     
    # Formating the parsed html file
    strhtm = soup.prettify()
     
    # Print first 500 lines
    print(strhtm[:500])
     
    # Extract meta tag value
    print(soup.title.string)
    print(soup.find('meta', attrs={ 'property':'og:description'}))
     
    # Extract anchor tag value
    for x in soup.find_all('a'):
        print(x.string)
     
    # Extract Paragraph tag value    
    for x in soup.find_all('p'):
        print(x.text)
    • 1
    • 2
    • 3

    读取 Json 数据

    import requests
    import json

    r = requests.get("https://support.oneskyapp.com/hc/en-us/article_attachments/202761727/example_2.json")
    res = r.json()

    # Extract specific node content.
    print(res['quiz']['sport'])

    # Dump data as string
    data = json.dumps(res)
    print(data)
    • 1

    读取 CSV 数据

    import csv

    with open('test.csv','r') as csv_file:
        reader =csv.reader(csv_file)
        next(reader) # Skip first row
        for row in reader:
            print(row)
    • 1

  • 相关阅读:
    如何写出让人抓狂的代码?
    YOLOv7训练自己的数据集(口罩检测)
    计算机网络概述(接入网和物理媒体)
    猿创征文|十年Java路漫漫,多少青丝已皓首
    Qt第六十五章:自定义菜单栏的隐藏、弹出
    常用Docker项目合集
    【6. N 字形变换】
    易基因|DNA甲基化和单细胞RNA-seq联合揭示空气污染对复发性流产的表观遗传影响
    记一次 .NET某账本软件 非托管泄露分析
    Eviews如何做VAR
  • 原文地址:https://blog.csdn.net/zhouwei_1989_/article/details/126549334
  • 最新文章
  • 沪漂五周年了:我越来越迷茫了
    Agentic Skill Routing 实战:别再把所有 Skill 塞进 AI Agent 上下文
    MySQL-Seconds_behind_master的精度误差
    [MAF预定义ChatClient中间件-03]CachingChatClient——利用缓存省钱省时间
    AI的至暗历史:从万众期待到被政府撤资,AI的两次死亡徘徊
    Agent OS :五种驯服不确定性的范式
    PortSwigger SQL注入LAB11
    数据库即时编译JIT
    [Begin]AI Learn Data Day 0
    深度学习进阶(二十七)现代 LLM 的核心架构设计其二:SwiGLU
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
小工具 小游戏
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1

京公网安备 11010502049817号