Python-data-science-python-processing-unstructured-data

提供:Dev Guides
移動先:案内検索

Python-非構造化データの処理

行と列の形式で既に存在するデータ、または後でデータベースにうまく収まるように行と列に簡単に変換できるデータは、構造化データと呼ばれます。 例は、CSV、TXT、XLSファイルなどです。 これらのファイルには、区切り文字と固定幅または可変幅のいずれかがあり、欠損値は区切り文字の間の空白として表されます。 ただし、行の幅が固定されていないデータや、単にHTML、画像、またはpdfファイルのデータを取得する場合があります。 このようなデータは、非構造化データと呼ばれます。 HTMLファイルはHTMLタグを処理することで処理できますが、ツイッターからのフィードまたはニュースフィードからのプレーンテキストドキュメントには、区切り文字がなくても処理するタグがありません。 このようなシナリオでは、さまざまな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})