I. 何をする?

Pythonにおける文字列の処理方法を学びます。

文字列を自由に処理できるようになれば、面倒な単純作業が軽減されます。

例えば、次の文字列から年齢の平均を計算できます。

# stringのarrayを作成
string = """
aso80
suga72
nikai82
takeshita74"""
print(string)
## 
## aso80
## suga72
## nikai82
## takeshita74

改行で分けて“名前+年齢”のtuplesのlistを作成します。

# split string by line breaks
chunks = string.split('\n')
def mysplit(s):
  head = s.rstrip('0123456789')
  tail = s[len(head):]
  return head, tail
list_of_tuples = [mysplit(i) for i in chunks]
print(list_of_tuples)
## [('', ''), ('aso', '80'), ('suga', '72'), ('nikai', '82'), ('takeshita', '74')]

データ・フレームを作成して、平均を算出します。

import pandas as pd
df = pd.DataFrame(list_of_tuples, columns = ['name', 'age'])
df.drop(df.index[0], inplace = True)
# convert age to integer
df['age'] = df['age'].astype(int)
df['age'].mean()
## 77.0

データ・フレームではなくて辞書を作成して算出することもできます。

# remove the first vacant item
del list_of_tuples[0]
# create dictionary from tuples
mydic = dict(list_of_tuples)
# convert values from string to integer 
mydic_ints = {k:int(v) for k, v in mydic.items()}
sum(mydic_ints.values()) / len(mydic)
## 77.0

II.Regular expressions

はじめに、次の解説にしたがって、文字を細かい設定で選び出すRegular expressionsを学びます。

Python Regular Expressions Tutorial and Examples: A Simplified Guide

サンプルの文字列を作成します。

mystring = """101 COM    Computers
205 MAT   Mathematics
189 ENG   English""" 
print(mystring)
## 101 COM    Computers
## 205 MAT   Mathematics
## 189 ENG   English

文字列のままでは処理できないので、スペースで分けて文字列のリストを作成します。

re.splitを使います。“\s”はspaceです。“+”を加えるとspacesです。

# split strings around 1 or more space characters
import re
re.split('\s+', mystring)
## ['101', 'COM', 'Computers', '205', 'MAT', 'Mathematics', '189', 'ENG', 'English']

To be continued.