
- Python 数据科学教程
- Python 数据科学 - 首页
- Python 数据科学 - 入门
- Python 数据科学 - 环境设置
- Python 数据科学 - Pandas
- Python 数据科学 - Numpy
- Python 数据科学 - SciPy
- Python 数据科学 - Matplotlib
- Python 数据处理
- Python 数据操作
- Python 数据清洗
- Python 处理 CSV 数据
- Python 处理 JSON 数据
- Python 处理 XLS 数据
- Python 关系型数据库
- Python NoSQL 数据库
- Python 日期和时间
- Python 数据整理
- Python 数据聚合
- Python 读取 HTML 页面
- Python 处理非结构化数据
- Python 词语分词
- Python 词干提取和词形还原
- Python 数据可视化
- Python 图表属性
- Python 图表样式
- Python 箱线图
- Python 热力图
- Python 散点图
- Python 气泡图
- Python 3D 图表
- Python 时间序列
- Python 地理数据
- Python 图数据
Python - 处理非结构化数据
已经以行和列格式存在或可以轻松转换为行和列以便稍后可以很好地放入数据库中的数据称为结构化数据。例如 CSV、TXT、XLS 文件等。这些文件具有分隔符,并且具有固定或可变宽度,其中缺失值表示为分隔符之间的空白。但有时我们会得到数据,其中行没有固定宽度,或者它们只是 HTML、图像或 pdf 文件。此类数据称为非结构化数据。虽然可以通过处理 HTML 标签来处理 HTML 文件,但来自 Twitter 的 feed 或来自新闻 feed 的纯文本文档在没有分隔符的情况下也没有标签来处理。在这种情况下,我们使用来自各种 Python 库的不同内置函数来处理文件。
读取数据
在下面的示例中,我们获取一个文本文件并读取该文件,将其中的每一行都分隔开。接下来,我们可以将输出进一步划分为行和单词。原始文件是一个文本文件,其中包含一些描述 Python 语言的段落。
filename = 'path\input.txt' with open(filename) as fn: # Read each line ln = fn.readline() # Keep count of lines lncnt = 1 while ln: print("Line {}: {}".format(lncnt, ln.strip())) ln = fn.readline() lncnt += 1
当我们执行上述代码时,它会产生以下结果。
Line 1: Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales. Line 2: Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library. Line 3: Python interpreters are available for many operating systems. CPython, the reference implementation of Python, is open source software and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.
计算词频
我们可以使用计数器函数如下计算文件中单词的频率。
from collections import Counter with open(r'pathinput2.txt') as f: p = Counter(f.read().split()) print(p)
当我们执行上述代码时,它会产生以下结果。
Counter({'and': 3, 'Python': 3, 'that': 2, 'a': 2, 'programming': 2, 'code': 1, '1991,': 1, 'is': 1, 'programming.': 1, 'dynamic': 1, 'an': 1, 'design': 1, 'in': 1, 'high-level': 1, 'management.': 1, 'features': 1, 'readability,': 1, 'van': 1, 'both': 1, 'for': 1, 'Rossum': 1, 'system': 1, 'provides': 1, 'memory': 1, 'has': 1, 'type': 1, 'enable': 1, 'Created': 1, 'philosophy': 1, 'constructs': 1, 'emphasizes': 1, 'general-purpose': 1, 'notably': 1, 'released': 1, 'significant': 1, 'Guido': 1, 'using': 1, 'interpreted': 1, 'by': 1, 'on': 1, 'language': 1, 'whitespace.': 1, 'clear': 1, 'It': 1, 'large': 1, 'small': 1, 'automatic': 1, 'scales.': 1, 'first': 1})
广告