- 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})
廣告