码农知识堂 - 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

  • 相关阅读:
    【华为OD机试真题 python】 【找单词】【2022 Q4 | 200分】
    这些Java基础知识,诸佬们都还记得嘛(学习,复习,面试都可)
    c语言从入门到实战——数组指针与函数指针
    固定资产台账怎么管理
    大语言模型(LLM)综述(七):大语言模型设计应用与未来方向
    Linux 实用的监控机器操作指令
    Uniapp矩阵评分组件
    论文日记五:QueryInst
    ES6 入门教程 8 函数的扩展 8.2 rest 参数 & 8.3 严格模式
    基于FFmpeg的Java视频Mp4转GIF初探
  • 原文地址:https://blog.csdn.net/zhouwei_1989_/article/details/126549334
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号