« 2020年5月 | トップページ | 2020年7月 »

2020年6月28日 (日)

[Visual Basic]正規表現を使って文字列を分割する

RegexクラスのSplitメソッドを使う。System.Text.RegularExpressions名前空間をインポートしておく。

以下は文字型変数sに代入した文字列「□A□BC□□DEF□□」(□は空白)を1つ以上の空白で分割した例。「1つ以上の空白」は正規表現では「[\s]+」となる。

分割元の文字列の前後の空白を同時に判定するのは表現が煩雑になるため、分割の前にTrimメソッドで、分割元の文字列の前後の空白を除去している。

Imports System.Text.RegularExpressions
Module Split
Sub Main()
Dim i As Integer
Dim s As String
Dim word() As String
s = " A BC DEF "
word = Regex.Split(s.Trim(), "[\s]+")
For i = 0 To word.GetLength(0) - 1
Console.WriteLine(Str(i) & ": " & word(i))
Next i
End Sub
End Module

出力

 0: A
1: BC
2: DEF

2020年6月26日 (金)

[Python]ファイルやディレクトリの存在を確認する

osモジュールのpath.exists関数を使う。path.exists関数は引数に与えたパスがファイルでもディレクトリでも存在していればTrueを返す。

ファイルかディレクトリの判定はpath.isfile関数かpath.isdir関数を使う。この両関数は、存在しないパスを指定するとFalseを返す。

>>> import os
>>> os.path.exists('C:\Windows\write.exe')
True
>>> os.path.exists('C:\Windows')
True
>>> os.path.exists('C:\Windows\write.ex')
False
>>> os.path.exists('C:\Win')
False
>>> os.path.isfile('C:\Windows\write.exe')
True
>>> os.path.isdir('C:\Windows\write.exe')
False
>>> os.path.isfile('C:\Windows')
False
>>> os.path.isdir('C:\Windows')
True
>>> os.path.isfile('C:\Win')
False
>>> os.path.isdir('C:\Win')
False

2020年6月25日 (木)

[Python]リストのリスト(2次元配列)を作る

リスト内包表記を使うことで簡単に作ることができる。

以下は、2行3列の空の2次元配列を作成した例。ここで i は繰り返し用に使用する変数であり、なんでもかまわない。

>>> x = [[None] * 3 for i in range(2)]
>>> x
[[None, None, None], [None, None, None]]

値を代入してみる。

>>> x[1][2] = 100
>>> x
[[None, None, None], [None, None, 100]]

2020年6月11日 (木)

[Python]空のリストを作る

リスト表記演算子 [ ] を使う。[ ] は空のリストを表す。

>>> x = []
>>> x
[]

2020年6月 2日 (火)

[R]データフレームを特定の列だけのデータフレームにする

インデックス付けを使う。取り出したい列の番号を連番で指定する。

> name <- c("a", "b", "c")
> age <- c(30, 10, 20)
> sex <- c("M", "F", "M")
> dtf <- data.frame(name, age, sex)
> dtf
name age sex
1 a 30 M
2 b 10 F
3 c 20 M
> dtf[, c(1, 3)]
name sex
1 a M
2 b F
3 c M
> dtf[, 2:3]
age sex
1 30 M
2 10 F
3 20 M

« 2020年5月 | トップページ | 2020年7月 »

無料ブログはココログ

■■

■■■