input
stringlengths 0
929
| output
stringlengths 0
10.3k
| task
stringclasses 3
values | index
int64 0
5.38k
| liscence
stringclasses 4
values | source
stringclasses 15
values | instruction
stringlengths 13
3.45k
|
---|---|---|---|---|---|---|
````julia
numGridPts = 5;
vX = LinRange(0, 1, numGridPts);
vY = LinRange(0, 1, numGridPts);
MeshGrid = (vX, vY) -> ([x for _ in vY, x in vX], [y for y in vY, _ in vX]);
mX, mY = MeshGrid(vX, vY); #<! See https://discourse.julialang.org/t/48679
@show mX
````
|
code_generation
| 500 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`[0,1]×[0,1]`の領域をカバーする`x`座標と`y`座標の格子を作成しなさい。
|
|
````julia
vX = rand(5);
vY = rand(5);
mC = 1 ./ (vX .- vY')
````
|
code_generation
| 501 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、2つのベクトル `vX` と `vY` が与えられたとき、コーシー行列 `mC`: `(Cij = 1 / (xi - yj))` を作りなさい。
|
|
````julia
vT = [UInt8 UInt16 UInt32 UInt64 Int8 Int16 Int32 Int64 Float16 Float32 Float64]
for juliaType in vT
println(typemin(juliaType));
println(typemax(juliaType));
end
````
|
code_generation
| 502 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、各 Julia スカラー型の表現可能な最小値と最大値を出力しなさい。
|
|
````julia
print(mA);
````
|
code_generation
| 503 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、配列mAのすべての値を表示しなさい。
|
|
````julia
inputVal = 0.5;
vA = rand(10);
vA[argmin(abs.(vA .- inputVal))]
````
|
code_generation
| 504 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、ベクトル内の指定されたスカラーに最も近い値を見つけなさい。
|
|
````julia
struct sPosColor
x::Int
y::Int
R::UInt8;
G::UInt8;
B::UInt8;
A::UInt8;
end
numPixels = 10;
maxVal = typemax(UInt32);
vMyColor = [sPosColor(rand(1:maxVal, 2)..., rand(UInt8, 4)...) for _ in 1:numPixels];
````
|
code_generation
| 505 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、位置 `(x, y)` と色 `(r, g, b)` を表す構造化配列を作成しなさい。
|
|
````julia
mX = rand(5, 2);
vSumSqr = sum(vX -> vX .^ 2, mX, dims = 2);
mD = vSumSqr .+ vSumSqr' - 2 * (mX * mX');
mD #<! Apply `sqrt.()` for the actual norm
````
|
code_generation
| 506 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、座標を表す形状 `(5, 2)` のランダムなベクトルを考え、距離行列 `mD` を求めよ: $ {D}_{i, j} = {left| {x}_{i} - {x}_{j}. \右|}_{2} $.
|
|
````julia
vA = 9999 .* rand(Float32, 5);
vB = reinterpret(Int32, vA); #<! Creates a view
@. vB = trunc(Int32, vA) #<! Updates the byes in th view (Inplace for `vA`)
````
|
code_generation
| 507 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、浮動小数点 (32 ビット) 配列をその場で整数 (32 ビット) に変換しなさい。
|
|
````julia
mA = readdlm("Q0054.txt", ',')
````
|
code_generation
| 508 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、次のファイル(Q0054.txt)を読んでください。
```
1, 2, 3, 4, 5
6, , , 7, 8
, , 9,10,11
```
|
|
````julia
mA = rand(3, 3);
for (elmIdx, elmVal) in enumerate(mA) #<! See https://discourse.julialang.org/t/48877
println(elmIdx);
println(elmVal);
end
````
|
code_generation
| 509 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、ループ内で配列を列挙しなさい。
|
|
````julia
vA = -5:5;
μ = 0;
σ = 1;
mG = [(1 / (2 * pi * σ)) * exp(-0.5 * ((([x, y] .- μ)' * ([x, y] .- μ)) / (σ * σ))) for x in vA, y in vA];
heatmap(mG)
````
|
code_generation
| 510 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`μ=0`、`σ=1`、インデックス `{-5, -4, ..., 0, 1, ..., 5}` の一般的な2次元ガウス型配列を生成しなさい。
|
|
````julia
mA = rand(5, 5);
mA[rand(1:25, 5)] = rand(5);
````
同じインデックスへの設定を避ける別のオプション:
````julia
mA[randperm(25)[1:5]] = rand(5);
````
|
code_generation
| 511 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`5x5` の配列に `5` 個の要素をランダムに配置する。
|
|
````julia
mA = rand(3, 3);
mA .-= mean(mA, dims = 2);
mean(mA, dims = 1)
````
|
code_generation
| 512 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、行列の各行の平均を減算しなさい。
|
|
````julia
colIdx = 2;
mA = rand(3, 3);
mA[sortperm(mA[:, colIdx]), :]
````
|
code_generation
| 513 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、配列を列でソートしなさい。
|
|
````julia
mA = rand(0:1, 3, 9);
any(all(iszero.(mA), dims = 1))
````
|
code_generation
| 514 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、指定された 2D 配列に null (すべてゼロ) 列があるかどうかを判断しなさい。
````julia
mA = rand(0:1, 3, 9);
````
|
|
````julia
inputVal = 0.5;
vA = rand(10);
vA[sortperm(abs.(vA .- inputVal))[2]]
````
より効率的な代替方法
````julia
closeFirst = Inf;
closeSecond = Inf;
closeFirstIdx = 0;
closeSecondIdx = 0;
# Using `global` for scope in Literate
for (elmIdx, elmVal) in enumerate(abs.(vA .- inputVal))
if (elmVal < closeFirst)
global closeSecond = closeFirst;
global closeFirst = elmVal;
global closeSecondIdx = closeFirstIdx;
global closeFirstIdx = elmIdx;
elseif (elmVal < closeSecond)
global closeSecond = elmVal;
global closeSecondIdx = elmIdx;
end
end
vA[closeSecondIdx] == vA[sortperm(abs.(vA .- inputVal))[2]]
````
|
code_generation
| 515 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、配列内の指定された値から 2 番目に近い値を検索しなさい。
|
|
````julia
vA = rand(1, 3);
vB = rand(3, 1);
sum(aVal + bVal for aVal in vA, bVal in vB)
````
|
code_generation
| 516 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`(1,3)`と(3,1)`の2つの配列を考え、イテレータを使ってそれらの和を計算する。
|
|
`NamedArrays.jl`や`AxisArrays.jl`を使うことができます。
|
code_generation
| 517 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、name属性を持つ配列クラスを作成しなさい。
|
|
````julia
vA = rand(1:10, 5);
vB = rand(1:5, 3);
println(vA);
# Julia is very efficient with loops
for bIdx in vB
vA[bIdx] += 1;
end
println(vA);
````
|
code_generation
| 518 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、ベクトルが与えられたとき、2番目のベクトルによってインデックス付けされた各要素に `1` を加えなさい(繰り返されるインデックスに注意)。
|
|
````julia
vX = rand(1:5, 10);
vI = rand(1:15, 10);
numElements = maximum(vI);
vF = zeros(numElements);
for (ii, iIdx) in enumerate(vI)
vF[iIdx] += vX[ii];
end
println("vX: $vX");
println("vI: $vI");
println("vF: $vF");
````
|
code_generation
| 519 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、インデックスリスト `I` に基づいて、ベクトル `X` の要素を配列 `F` に累積しなさい。
|
|
````julia
mI = rand(UInt8, 1000, 1000, 3);
numColors = length(unique([reinterpret(UInt32, [iPx[1], iPx[2], iPx[3], 0x00])[1] for iPx in eachrow(reshape(mI, :, 3))])); #<! Reshaping as at the moment `eachslice()` doesn't support multiple `dims`.
print("Number of Unique Colors: $numColors");
````
Another option:
````julia
numColors = length(unique([UInt32(iPx[1]) + UInt32(iPx[2]) << 8 + UInt32(iPx[3]) << 16 for iPx in eachrow(reshape(mI, :, 3))]));
print("Number of Unique Colors: $numColors");
````
Simpler way to slice a pixel:
````julia
numColors = length(unique([UInt32(mI[ii, jj, 1]) + UInt32(mI[ii, jj, 2]) << 8 + UInt32(mI[ii, jj, 3]) << 16 for ii in 1:size(mI, 1), jj in 1:size(mI, 2)]));
print("Number of Unique Colors: $numColors");
````
|
code_generation
| 520 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、サイズ `w x h x 3` の `UInt8` 型の画像を考えて、ユニークな色の数を計算しなさい。
|
|
````julia
mA = rand(2, 2, 2, 2);
sum(reshape(mA, (2, 2, :)), dims = 3)
````
````
2×2×1 Array{Float64, 3}:
[:, :, 1] =
1.817 1.16234
2.44291 2.32796
````
|
code_generation
| 521 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、4次元の配列を考えて、最後の2軸の和を一度に取得しなさい。
|
|
````julia
# Bascially extending `Q0065` with another vector of number of additions.
vX = rand(1:5, 10);
vI = rand(1:15, 10);
numElements = maximum(vI);
vF = zeros(numElements);
vN = zeros(Int, numElements);
for (ii, iIdx) in enumerate(vI)
vF[iIdx] += vX[ii];
vN[iIdx] += 1;
end
# We only divide the mean if the number of elements accumulated is bigger than 1
for ii in 1:numElements
vF[ii] = ifelse(vN[ii] > 1, vF[ii] / vN[ii], vF[ii]);
end
println("vX: $vX");
println("vI: $vI");
println("vF: $vF");
````
|
code_generation
| 522 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、1次元のベクトル `vA` を考えたとき、部分集合のインデックスを記述した同じ大きさのベクトル `vS` を用いて `vA` の部分集合の平均を計算しなさい。
|
|
````julia
mA = rand(5, 7);
mB = rand(7, 4);
numDiagElements = min(size(mA, 1), size(mB, 2));
vD = [dot(mA[ii, :], mB[:, ii]) for ii in 1:numDiagElements]
````
````
4-element Vector{Float64}:
1.8937792321469207
1.035584608236753
2.0251852803210024
2.2065505485118653
````
別の方法:
````julia
vD = reshape(sum(mA[1:numDiagElements, :]' .* mB[:, 1:numDiagElements], dims = 1), numDiagElements)
````
|
code_generation
| 523 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、行列積の対角を取得しなさい。
|
|
````julia
vA = 1:5;
# Since Julia is fast with loops, it would be the easiest choice
numElements = (4 * length(vA)) - 3;
vB = zeros(Int, numElements);
for (ii, bIdx) in enumerate(1:4:numElements)
vB[bIdx] = vA[ii];
end
println(vB);
# Alternative (MATLAB style) way:
mB = [reshape(collect(vA), 1, :); zeros(Int, 3, length(vA))];
vB = reshape(mB[1:(end - 3)], :);
println(vB);
````
|
code_generation
| 524 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、ベクトル`[1, 2, 3, 4, 5]`を考え、各値の間に連続する3つのゼロを挟んだ新しいベクトルを作りなさい。
|
|
````julia
mA = rand(5, 5, 3);
mB = rand(5, 5);
mA .* mB #<! Very easy in Julia
````
|
code_generation
| 525 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`5 x 5 x 3`の次元の配列を考え、ブロードキャストを使って5 x 5`の次元の配列を乗算しなさい。
|
|
````julia
mA = rand(UInt8, 3, 2);
println(mA);
mA[[1, 2], :] .= mA[[2, 1], :];
println(mA);
````
|
code_generation
| 526 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、2D 配列の 2 つの行を交換しなさい。
|
|
````julia
mA = rand(0:100, 10, 3); #<! Each row composes 3 veritces ([1] -> [2], [2] -> [3], [3] -> [1])
mC = [sort!([vC[mod1(ii, end)], vC[mod1(ii + 1, end)]]) for ii in 1:(size(mA, 2) + 1), vC in eachrow(mA)][:] #<! Sorted combinations of vertices
mC = unique(mC)
````
|
code_generation
| 527 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、10 個の三角形 (頂点を共有) を表す 10 個のトリプレットのセットを考え、すべての三角形を構成する一意の線分のセットを見つけます。
|
|
````julia
vC = rand(0:7, 5);
numElements = sum(vC);
vA = zeros(Int, numElements);
elmIdx = 1;
# Using `global` for scope in Literate
for (ii, binCount) in enumerate(vC)
for jj in 1:binCount
vA[elmIdx] = ii;
global elmIdx += 1;
end
end
````
|
code_generation
| 528 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、bincount に対応する並べ替えられた配列 `vC` が与えられたとき、 `bincount(vA) == vC` となるような配列 `vA` を生成する。
|
|
````julia
numElements = 10;
winRadius = 1;
winReach = 2 * winRadius;
winLength = 1 + winReach;
vA = rand(0:3, numElements);
vB = zeros(numElements - (2 * winRadius));
aIdx = 1 + winRadius;
# Using `global` for scope in Literate
for ii in 1:length(vB)
vB[ii] = mean(vA[(aIdx - winRadius):(aIdx + winRadius)]); #<! Using integral / running sum it would be faster.
global aIdx += 1;
end
````
累計を使用する別の方法:
````julia
vC = zeros(numElements - winReach);
jj = 1;
sumVal = sum(vA[1:winLength]);
vC[jj] = sumVal / winLength;
jj += 1;
# Using `global` for scope in Literate
for ii in 2:(numElements - winReach)
global sumVal += vA[ii + winReach] - vA[ii - 1];
vC[jj] = sumVal / winLength;
global jj += 1;
end
maximum(abs.(vC - vB)) < 1e-8
````
|
code_generation
| 529 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、配列に対してスライディング ウィンドウを使用して平均を計算します。
|
|
````julia
vA = rand(10);
numCols = 3;
numRows = length(vA) - numCols + 1;
mA = zeros(numRows, numCols);
for ii in 1:numRows
mA[ii, :] = vA[ii:(ii + numCols - 1)]; #<! One could optimize the `-1` out
end
````
|
code_generation
| 530 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、1次元配列 `vA` を考え、最初の行を `[ vA[0], vA[1], vA[2] ]` とし、それ以降の行を1ずつシフトした2次元配列を作りなさい。
|
|
````julia
vA = rand(Bool, 10);
vA .= .!vA;
vA = randn(10);
vA .*= -1;
````
|
code_generation
| 531 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、ブール値を否定するか、フロートの符号をその場で変更しなさい。
|
|
````julia
# See distance of a point from a line in Wikipedia (https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line).
# Specifically _Line Defined by Two Points_.
numLines = 10;
mP1 = randn(numLines, 2);
mP2 = randn(numLines, 2);
vP = randn(2);
vD = [(abs(((vP2[1] - vP1[1]) * (vP1[2] - vP[2])) - ((vP1[1] - vP[1]) * (vP2[2] - vP1[2]))) / hypot((vP2 - vP1)...)) for (vP1, vP2) in zip(eachrow(mP1), eachrow(mP2))];
minDist = minimum(vD);
println("Min Distance: $minDist");
````
|
code_generation
| 532 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、直線(2d)を記述する2組の点 `mP1`, `mP2` と点 `vP` を考え、点 `vP` から各直線 `i` までの距離 `[mP1[i, :], mP2[i, :]` を計算する。
|
|
````julia
numLines = 5;
mP1 = randn(numLines, 2);
mP2 = randn(numLines, 2);
mP = randn(numLines, 2);
mD = [(abs(((vP2[1] - vP1[1]) * (vP1[2] - vP[2])) - ((vP1[1] - vP[1]) * (vP2[2] - vP1[2]))) / hypot((vP2 - vP1)...)) for (vP1, vP2) in zip(eachrow(mP1), eachrow(mP2)), vP in eachrow(mP)];
for jj in 1:numLines
minDist = minimum(mD[jj, :]);
println("The minimum distance from the $jj -th point: $minDist");
end
````
|
code_generation
| 533 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、直線(2d)を記述する2つの点の集合 `mP1`, `mP2` と点の集合 `mP` を考えるとき、点 `vP = mP[j, :]` から各直線 `i` までの距離 `[mP1[i, :], mP2[i, :]` はどのように計算するか考えなさい。
|
|
````julia
# One could use `PaddedViews.jl` to easily solve this.
arrayLength = 10;
winRadius = 3;
vWinCenter = [7, 9];
mA = rand(arrayLength, arrayLength);
winLength = (2 * winRadius) + 1;
mB = zeros(winLength, winLength);
verShift = -winRadius;
# Using `global` for scope in Literate
for ii in 1:winLength
horShift = -winRadius;
for jj in 1:winLength
mB[ii, jj] = mA[min(max(vWinCenter[1] + verShift, 1), arrayLength), min(max(vWinCenter[2] + horShift, 1), arrayLength)]; #<! Nearest neighbor extrapolation
horShift += 1;
end
global verShift += 1;
end
````
|
code_generation
| 534 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、任意の2次元配列を考え、与えられた要素を中心として、一定の形状を持つ部分部分(Handelは範囲外)を抽出する関数を書きなさい。
|
|
````julia
vA = collect(1:14);
winNumElements = 4;
winReach = winNumElements - 1;
vB = [vA[ii:(ii + winReach)] for ii in 1:(length(vA) - winReach)]
````
|
code_generation
| 535 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、配列 `vA = [1, 2, 3, ..., 13, 14]` を考え、配列 `vB = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], ..., [11, 12, 13, 14]]` を生成しなさい。
|
|
````julia
numRows = 5;
numCols = 4;
mA = randn(numRows, numCols);
rank(mA)
````
|
code_generation
| 536 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、マトリックスのランクを計算しなさい。
|
|
````julia
vA = rand(1:5, 15);
````
MATLAB Style (Manual loop might be faster)
````julia
vB = unique(vA);
# vB[argmax(sum(vA .== vB', dims = 1)[:])] #<! The input to `argmax()` is a `1 x n` vector, hence squeezed so `argmax()` won't return Cartesian Index.
vB[argmax(dropdims(sum(vA .== vB', dims = 1), dims = 1))] #<! The input to `argmax()` is a `1 x n` vector, hence squeezed so `argmax()` won't return Cartesian Index.
````
ビットの比較:
ビットレベルで整数に変換し、counts()from のようなものを使用することもできますStatsBase.jl。1:4 バイトのデータをサポート:
```julia
numBytes = sizeof(vA[1]);
if (sizeof(vA[1]) == 1)
vB = reinterpret(UInt8, vA);
elseif (sizeof(vA[1]) == 2)
vB = reinterpret(UInt16, vA);
elseif (sizeof(vA[1]) == 4)
vB = reinterpret(UInt32, vA);
elseif (sizeof(vA[1]) == 8)
vB = reinterpret(UInt64, vA);
end
```
|
code_generation
| 537 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、配列内で最も頻度の高い値を見つけなさい。
|
|
````julia
numRows = 5;
numCols = 5;
mA = rand(1:9, numRows, numCols);
winRadius = 1;
winReach = 2 * winRadius;
winLength = winReach + 1;
mB = [mA[ii:(ii + winReach), jj:(jj + winReach)] for ii in 1:(numRows - winReach), jj in 1:(numCols - winReach)]
````
|
code_generation
| 538 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`5x5` のランダムな行列から、連続する `3x3` のブロックをすべて取り出す。
|
|
````julia
struct SymmetricMatrix{T <: Number} <: AbstractArray{T, 2}
numRows::Int
data::Matrix{T}
function SymmetricMatrix(mA::Matrix{T}) where {T <: Number}
size(mA, 1) == size(mA, 2) || throw(ArgumentError("Input matrix must be square"))
new{T}(size(mA, 1), Matrix(Symmetric(mA)));
end
end
function Base.size(mA::SymmetricMatrix)
(mA.numRows, mA.numRows);
end
function Base.getindex(mA::SymmetricMatrix, ii::Int)
mA.data[ii];
end
function Base.getindex(mA::SymmetricMatrix, ii::Int, jj::Int)
mA.data[ii, jj];
end
function Base.setindex!(mA::SymmetricMatrix, v, ii::Int, jj::Int)
setindex!(mA.data, v, ii, jj);
setindex!(mA.data, v, jj, ii);
end
mA = SymmetricMatrix(zeros(Int, 2, 2));
mA[1, 2] = 5;
mA
````
|
code_generation
| 539 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`mA[i,j]==mA[j,i]`(対称行列)となるような2次元配列構造体を作成しなさい。
|
|
````julia
# One could use `TensorOperations.jl` or `Einsum.jl` for a more elegant solution.
numRows = 5;
numMat = 3;
tP = [randn(numRows, numRows) for _ in 1:numMat];
mP = [randn(numRows) for _ in 1:numMat];
vA = reduce(+, (mP * vP for (mP, vP) in zip(tP, mP)));
````
````julia
vB = zeros(numRows);
for ii in 1:numMat
vB .+= tP[ii] * mP[ii];
end
vA == vB
````
|
code_generation
| 540 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`nxn` の `p` 個の行列の集合と、長さ `n` の `p` 個のベクトルの集合を考える。`p` 個の行列のベクトル積の和を一度に計算せよ(結果は長さ `n` のベクトル)。
|
|
````julia
numRows = 16;
numCols = 8;
vBlockSize = [2, 4]; #<! [numRows, numCols] ./ vBlockSize == integer
mA = rand(numRows, numCols);
numBlocksVert = numRows ÷ vBlockSize[1];
numBlocksHori = numCols ÷ vBlockSize[2];
numBlocks = numBlocksVert * numBlocksHori;
mA = reshape(mA, vBlockSize[1], :);
````
ブロックを列ごとに番号付けし、リシェイプされた`mA`の列ごとにブロックインデックスを作成する。
````julia
vBlockIdx = 1:numBlocks;
mBlockIdx = reshape(vBlockIdx, numBlocksVert, numBlocksHori);
mBlockIdx = repeat(mBlockIdx, 1, 1, vBlockSize[2]);
mBlockIdx = permutedims(mBlockIdx, (1, 3, 2));
vBlockIdx = mBlockIdx[:]; #<! Matches the block index per column of the reshaped `mA`.
vA = dropdims(sum(mA, dims = 1), dims = 1);
vB = zeros(numBlocks);
for ii = 1:(numBlocks * vBlockSize[2])
vB[vBlockIdx[ii]] += vA[ii];
end
vB
````
|
code_generation
| 541 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`16x16`の配列を考え、ブロック和を計算しなさい(ブロックサイズは`4x4`)。あらゆるサイズのブロックについて、より一般的なケースを解決しなさい。
|
|
````julia
numRows = 20;
numCols = 20;
gofKernel = @kernel w -> w[-1, -1] + w[-1, 0] + w[-1, 1] + w[0, -1] + w[0, 1] + w[1, -1] + w[1, 0] + w[1, 1];
gofNumLives = round(Int, 0.05 * numRows * numCols);
gofNumGenerations = 50;
vI = randperm(numRows * numCols)[1:gofNumLives];
mG = zeros(UInt8, numRows, numCols);
mG[vI] .= UInt8(1);
mB = similar(mG);
heatmap(mG) #<! Initialization
````
|
code_generation
| 542 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、配列を使用してシミュレーションライフ ゲームを実装しなさい。
|
|
````julia
vA = rand(10);
numValues = 3;
vA[partialsortperm(vA, 1:numValues, rev = true)]
````
|
code_generation
| 543 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、配列の最大値 `n` を取得しなさい。
|
|
````julia
function CartesianProduct(tupleX)
return collect(Iterators.product(tupleX...))[:];
end
vA = 1:3;
vB = 8:9;
vC = 4:5;
CartesianProduct((vA, vB, vC))
````
|
code_generation
| 544 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、任意の数のベクトルを指定して、デカルト積(すべての項目のすべての組み合わせ) を構築しなさい。
|
|
`StructArrays.jl`を使うことができます。
|
code_generation
| 545 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、NumPy_の_record array_のようにアクセスできる配列を作成しなさい。
|
|
方法001:
````julia
vB = vA .^ 3;
````
方法002:
````julia
vC = [valA ^ 3 for valA in vA];
````
方法003:
````julia
vD = zeros(length(vA));
for (ii, valA) in enumerate(vA)
vD[ii] = valA * valA * valA;
end
````
````julia
vB ≈ vC ≈ vD
````
|
code_generation
| 546 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、大きなベクトル `vA` を考え、3つの異なる方法を用いて `vA` の3乗を計算しなさい。
|
|
````julia
mA = rand(0:4, 8, 3);
mB = rand(0:4, 2, 2);
mC = [any(vA .== vB') for vB in eachrow(mB), vA in eachrow(mA)]; #<! General solution, will work for any size of `mA` and `mB`
vD = [all(vC) for vC in eachcol(mC)]
````
中間配列 `mC` を用いない解を得るためには、次のようにする。
````julia
function Iterate2(iA; iterState = missing)
if(ismissing(iterState))
valA, iterState = iterate(iA);
else
valA, iterState = iterate(iA, iterState);
end
valB, iterState = iterate(iA, iterState);
return (valA, valB), iterState
end
tT = (any(vA .== vB') for vB in eachrow(mB), vA in eachrow(mA));
iterState = missing;
vE = zeros(Bool, size(mA, 1));
for ii = 1:length(vD)
global iterState;
(valA, valB), iterState = Iterate2(tT; iterState = iterState);
vE[ii] = valA && valB;
end
vD == vE
````
|
code_generation
| 547 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`8x3` と `2x2` の2つの配列 `mA` と `mB` を考えた場合に、
`mB` の要素の順序に関係なく `mB` の各行の要素を含む `mA` の行を求めよ。質問の解釈は、`mB`の各行の要素を少なくとも1つ含む`mA`の行である。
|
|
````julia
mA = rand(1:3, 10, 3);
vD = [maximum(vA) != minimum(vA) for vA in eachrow(mA)]
````
|
code_generation
| 548 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、`10x3` の行列を考え、不等な値を持つ行を抽出しなさい。
|
|
````julia
vA = rand(UInt8, 10);
mB = zeros(Bool, length(vA), 8);
# See https://discourse.julialang.org/t/26663
for ii in 1:length(vA)
vS = bitstring(vA[ii]);
for jj in 1:size(mB, 2)
mB[ii, jj] = vS[jj] == '1';
end
end
mB
````
|
code_generation
| 549 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、int のベクトルを行列のバイナリ表現に変換しなさい。
|
|
````julia
mA = UInt8.(rand(1:3, 10, 3));
vS = [reduce(*, bitstring(valA) for valA in vA) for vA in eachrow(mA)]; #<! Supports any array!
vU = unique(vS);
vI = [findfirst(valU .== vS) for valU in vU];
````
別の方法:
````julia
vB = indexin(vU, vS);
vB == vI
````
|
code_generation
| 550 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、2 次元配列を指定して、一意の行を抽出しなさい。
|
|
````julia
vA = rand(5);
vB = rand(5);
````
内積
````julia
@tullio tullioVal = vA[ii] * vB[ii];
tullioVal ≈ dot(vA, vB) #<! Inner product
````
````
true
````
外積
````julia
@tullio mTullio[ii, jj] := vA[ii] * vB[jj]; #<! Outer product
mTullio ≈ vA * vB'
````
````
true
````
和
````julia
@tullio tullioVal = vA[ii];
tullioVal ≈ sum(vA) #<! Sum
````
````
true
````
乗算
````julia
@tullio vTullio[ii] := vA[ii] * vB[ii];
vTullio ≈ vA .* vB #<! Multiplication
````
````
true
````
|
code_generation
| 551 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、2つのベクトル `vA` と `vB` について、inner、outer、sum、mul 関数の einsum 等価値(`Einsum.jl` を使用)を書きなさい。
|
|
````julia
numPts = 100;
numSegments = 1000;
vX = sort(10 * rand(numPts));
vY = sort(10 * rand(numPts));
vR = cumsum(hypot.(diff(vX), diff(vY)));
pushfirst!(vR, 0.0);
vRSegment = LinRange(0.0, vR[end], numSegments);
struct LinearInterpolator1D{T <: Number} <: AbstractArray{T, 1}
vX::Vector{T};
vY::Vector{T};
function LinearInterpolator1D(vX::Vector{T}, vY::Vector{T}) where {T <: Number}
length(vX) == length(vX) || throw(ArgumentError("Input vectors must have the same length"));
new{T}(vX, vY);
end
end
function Base.size(vA::LinearInterpolator1D)
size(vA.vX);
end
function Base.getindex(vA::LinearInterpolator1D, ii::Number)
if (ii >= vA.vX[end])
return vA.vY[end];
end
if (ii <= vA.vX[1])
return vA.vY[1];
end
rightIdx = findfirst(vA.vX .>= ii);
leftIdx = rightIdx - 1;
tt = (ii - vA.vX[leftIdx]) / (vA.vX[rightIdx] - vA.vX[leftIdx]);
return ((1 - tt) * vA.vY[leftIdx]) + (tt * vA.vY[rightIdx]);
end
function Base.setindex!(vA::LinearInterpolator1D, valX, valY, ii::Int, jj::Int)
setindex!(sLinInterp.vX, valX, ii);
setindex!(sLinInterp.vY, valY, ii);
end
vXInt = LinearInterpolator1D(vR, vX);
vYInt = LinearInterpolator1D(vR, vY);
vXSegment = [vXInt[intIdx] for intIdx in vRSegment];
vYSegment = [vYInt[intIdx] for intIdx in vRSegment];
hP = lineplot(vX, vY, canvas = DotCanvas, name = "Samples");
lineplot!(hP, vXSegment, vYSegment, name = "Interpolated");
hP
````
|
code_generation
| 552 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、2つのベクトル `vX` と `vY` で記述される経路を考え、等距離のサンプルを使ってサンプリングしなさい。
|
|
````julia
mA = rand([0, 0.5, 1, 2, 3], 15, 3);
sumVal = 4;
vI = [all(vA .== round.(vA)) && sum(vA) == sumVal for vA in eachrow(mA)];
````
|
code_generation
| 553 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、整数 `n` と2次元配列 `mA` が与えられたとき、 `n` の多項分布からの抽選と解釈できる行を求めよ(整数のみを含み、和が `n` となる行)。
|
|
````julia
numTrials = 10000;
numSamples = 1000;
μ = 0.5;
vA = μ .+ randn(numSamples);
tM = (mean(vA[rand(1:numSamples, numSamples)]) for _ in 1:numTrials);
quantile(tM, [0.025, 0.975])
````
|
code_generation
| 554 |
The Unliscence
|
100_julia_exercises
|
Juliaを用いて、1次元配列 `vA` の平均について、ブートストラップした 95%信頼区間を計算します。つまり、配列の要素をN回置換して再標本化し、各標本の平均を計算し、その平均に対するパーセンタイルを計算しなさい。
|
|
text = 'stressed'
print(text[::-1])
|
code_generation
| 555 |
MIT
|
nlp_100_knocks
|
pythonを用いて、文字列”stressed”の文字を逆に(末尾から先頭に向かって)並べた文字列を表示しなさい。
|
|
text = 'パタトクカシーー'
print(text[1::2])
|
code_generation
| 556 |
MIT
|
nlp_100_knocks
|
pythonを用いて、「パタトクカシーー」という文字列の1,3,5,7文字目を取り出して連結した文字列を表示しなさい。
|
|
text0 = 'パトカー'
text1 = 'タクシー'
ans = ''
for i in range(len(text0)):
ans += text0[i]
ans += text1[i]
print(ans)
|
code_generation
| 557 |
MIT
|
nlp_100_knocks
|
pythonを用いて、「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を表示しなさい。
|
|
raw_text = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.'
text = raw_text.replace('.', '').replace(',', '')
ans = [len(w) for w in text.split()]
print(ans)
|
code_generation
| 558 |
MIT
|
nlp_100_knocks
|
pythonを用いて、“Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ。
|
|
def extract_chars(i, word):
if i in [1, 5, 6, 7, 8, 9, 15, 16, 19]:
return (word[0], i)
else:
return (word[:2], i)
raw_text = 'Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.'
text = raw_text.replace('.', '').replace(',', '')
ans = [extract_chars(i, w) for i, w in enumerate(text.split(), 1)]
print(dict(ans))
|
code_generation
| 559 |
MIT
|
nlp_100_knocks
|
pythonを用いて、“Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.”という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭の2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ。
|
|
def n_gram(target, n):
return [target[idx:idx + n] for idx in range(len(target) - n + 1)]
text = 'I am an NLPer'
for i in range(1, 4):
print(n_gram(text, i))
print(n_gram(text.split(' '), i))
|
code_generation
| 560 |
MIT
|
nlp_100_knocks
|
pythonを用いて、与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.この関数を用い,”I am an NLPer”という文から単語bi-gram,文字bi-gramを表示しなさい。
|
|
def n_gram(target, n):
return [target[idx:idx + n] for idx in range(len(target) - n + 1)]
X_text = 'paraparaparadise'
Y_text = 'paragraph'
X = n_gram(X_text, 2)
Y = n_gram(Y_text, 2)
print(f'和集合: {set(X) | set(Y)}')
print(f'積集合: {set(X) & set(Y)}')
print(f'差集合: {set(X) - set(Y)}')
print('se' in (set(X) & set(Y)))
|
code_generation
| 561 |
MIT
|
nlp_100_knocks
|
pythonを用いて、“paraparaparadise”と”paragraph”に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,’se’というbi-gramがXおよびYに含まれるかどうかを調べなさい。
|
|
def generate_text(x, y, z):
return f'{x}時の{y}は{z}'
x = 12
y = '気温'
z = 22.4
print(generate_text(x, y, z))
|
code_generation
| 562 |
MIT
|
nlp_100_knocks
|
pythonを用いて、引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.さらに,x=12, y=”気温”, z=22.4として,実行結果を確認しなさい。
|
|
def cipher(text):
text = [chr(219 - ord(w)) if 97 <= ord(w) <= 122 else w for w in text]
return ''.join(text)
text = 'this is a message.'
ans = cipher(text)
print(ans)
ans = cipher(ans)
print(ans)
|
code_generation
| 563 |
MIT
|
nlp_100_knocks
|
pythonを用いて、与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装しなさい。
・英小文字ならば(219 - 文字コード)の文字に置換
・その他の文字はそのまま出力
また、この関数を用い,英語のメッセージを暗号化・復号化しなさい。
|
|
import random
def shuffle_word(word):
if len(word) <= 4:
return word
else:
start = word[0]
end = word[-1]
others = random.sample(list(word[1:-1]), len(word[1:-1]))
return ''.join([start] + others + [end])
text = 'I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .'
ans = [shuffle_word(w) for w in text.split()]
print(' '.join(ans))
|
code_generation
| 564 |
MIT
|
nlp_100_knocks
|
pythonを用いて、スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成しなさい。ただし、長さが4以下の単語は並び替えないこととする。適当な英語の文(例えば”I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .”)を与え、その実行結果を確認せよ。
|
|
import pandas as pd
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
print(len(df))
wc -l ch02/popular-names.txt
|
code_generation
| 565 |
MIT
|
nlp_100_knocks
|
pythonを用いて、行数をカウントせよ.確認にはwcコマンドを用いよ。
|
|
import pandas as pd
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
df.to_csv('ch02/ans11.txt', sep=' ', index=False, header=None)
sed -e 's/[[:cntrl:]]/ /g' ch02/popular-names.txt >> ch02/ans11.txt
|
code_generation
| 566 |
MIT
|
nlp_100_knocks
|
pythonを用いて、タブ1文字につきスペース1文字に置換せよ。確認にはsedコマンド、trコマンド、もしくはexpandコマンドを用いよ。
|
|
import pandas as pd
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
df[0].to_csv('ch02/col1.txt', index=False, header=None)
df[1].to_csv('ch02/col2.txt', index=False, header=None)
cut -f1 -d$'\t' ch02/popular-names.txt >> ch02/col1.txt
cut -f2 -d$'\t' ch02/popular-names.txt >> ch02/col2.txt
|
code_generation
| 567 |
MIT
|
nlp_100_knocks
|
pythonを用いて、各行の1列目だけを抜き出したものをcol1.txtに、2列目だけを抜き出したものをcol2.txtとしてファイルに保存せよ。確認にはcutコマンドを用いよ。
|
|
import pandas as pd
c1 = pd.read_csv('ch02/col1.txt', header=None)
c2 = pd.read_csv('ch02/col2.txt', header=None)
df = pd.concat([c1, c2], axis=1)
df.to_csv('ch02/ans13.txt', sep='\t', index=False, header=None)
paste ch02/col1.txt ch02/col2.txt >> ch02/ans13.txt
|
code_generation
| 568 |
MIT
|
nlp_100_knocks
|
pythonを用いて、col1.txtとcol2.txtを結合し、元のファイルの1列目と2列目をタブ区切りで並べたテキストファイルを作成せよ。確認にはpasteコマンドを用いよ。
import pandas as pd
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
df[0].to_csv('ch02/col1.txt', index=False, header=None)
df[1].to_csv('ch02/col2.txt', index=False, header=None)
|
|
import sys
import pandas as pd
if len(sys.argv) == 1:
print('Set arg n, like "python ch02/ans14.py 5"')
else:
n = int(sys.argv[1])
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
print(df.head(n))
head -n $1 ch02/popular-names.txt
|
code_generation
| 569 |
MIT
|
nlp_100_knocks
|
pythonを用いて、自然数Nをコマンドライン引数などの手段で受け取り、入力のうち先頭のN行だけを表示せよ。確認にはheadコマンドを用いよ。
|
|
import sys
import pandas as pd
if len(sys.argv) == 1:
print('Set arg n, like "python ch02/ans15.py 5"')
else:
n = int(sys.argv[1])
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
print(df.tail(n))
tail -n $1 ch02/popular-names.txt
|
code_generation
| 570 |
MIT
|
nlp_100_knocks
|
pythonを用いて、自然数Nをコマンドライン引数などの手段で受け取り、入力のうち末尾のN行だけを表示せよ。確認にはtailコマンドを用いよ。
|
|
import sys
import pandas as pd
if len(sys.argv) == 1:
print('Set arg n, like "python ch02/ans15.py 5"')
else:
n = int(sys.argv[1])
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
nrow = -(-len(df) // n)
for i in range(n):
df.loc[nrow * i:nrow * (i + 1)].to_csv(f'ch02/ans16_{i}', sep='\t', index=False, header=None)
n=`wc -l ch02/popular-names.txt | awk '{print $1}'`
ln=`expr $n / $1`
split -l $ln ch02/popular-names.txt ch02/ans16_
|
code_generation
| 571 |
MIT
|
nlp_100_knocks
|
pythonを用いて、自然数Nをコマンドライン引数などの手段で受け取り、入力のファイルを行単位でN分割せよ。同様の処理をsplitコマンドで実現せよ。
|
|
import pandas as pd
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
print(df[0].unique())
cut -f1 -d$'\t' ch02/popular-names.txt | LANG=C sort | uniq
|
code_generation
| 572 |
MIT
|
nlp_100_knocks
|
pythonを用いて、1列目の文字列の種類(異なる文字列の集合)を求めよ。確認にはcut、 sort、 uniqコマンドを用いよ。
|
|
import pandas as pd
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
print(df.sort_values(2, ascending=False))
sort -r -k 3 -t $'\t' ch02/popular-names.txt
|
code_generation
| 573 |
MIT
|
nlp_100_knocks
|
pythonを用いて、各行を3コラム目の数値の逆順で整列せよ(注意: 各行の内容は変更せずに並び替えよ)。確認にはsortコマンドを用いよ(この問題はコマンドで実行した時の結果と合わなくてもよい)。
|
|
import pandas as pd
df = pd.read_csv('ch02/popular-names.txt', sep='\t', header=None)
print(df[0].value_counts())
cut -f1 -d$'\t' ch02/popular-names.txt | LANG=C sort | uniq -c | sort -r -k 2 -t ' '
|
code_generation
| 574 |
MIT
|
nlp_100_knocks
|
pythonを用いて、各行の1列目の文字列の出現頻度を求め、その高い順に並べて表示せよ。確認にはcut、uniq、sortコマンドを用いよ。
|
|
import pandas as pd
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
print(uk_text)
|
code_generation
| 575 |
MIT
|
nlp_100_knocks
|
pythonを用いて、Wikipedia記事のJSONファイルを読み込み、「イギリス」に関する記事本文を表示せよ。問題21-29では、ここで抽出した記事本文に対して実行せよ。
|
|
import pandas as pd
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
uk_texts = uk_text.split('\n')
ans = list(filter(lambda x: '[Category:' in x, uk_texts))
print(ans)
|
code_generation
| 576 |
MIT
|
nlp_100_knocks
|
pythonを用いて、記事中でカテゴリ名を宣言している行を抽出せよ。
|
|
import pandas as pd
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
uk_texts = uk_text.split('\n')
ans = list(filter(lambda x: '[Category:' in x, uk_texts))
ans = [a.replace('[[Category:', '').replace('|*', '').replace(']]', '') for a in ans]
print(ans)
|
code_generation
| 577 |
MIT
|
nlp_100_knocks
|
pythonを用いて、記事のカテゴリ名を(行単位ではなく名前で)抽出せよ。
|
|
import re
import pandas as pd
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
for section in re.findall(r'(=+)([^=]+)\1\n', uk_text):
print(f'{section[1].strip()}\t{len(section[0]) - 1}')
|
code_generation
| 578 |
MIT
|
nlp_100_knocks
|
pythonを用いて、記事中に含まれるセクション名とそのレベル(例えば”== セクション名 ==”なら1)を表示せよ。
|
|
import re
import pandas as pd
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
for file in re.findall(r'\[\[(ファイル|File):([^]|]+?)(\|.*?)+\]\]', uk_text):
print(file[1])
|
code_generation
| 579 |
MIT
|
nlp_100_knocks
|
pythonを用いて、記事から参照されているメディアファイルをすべて抜き出せ。
|
|
import re
import pandas as pd
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
uk_texts = uk_text.split('\n')
pattern = re.compile('\|(.+?)\s=\s*(.+)')
ans = {}
for line in uk_texts:
r = re.search(pattern, line)
if r:
ans[r[1]] = r[2]
print(ans)
|
code_generation
| 580 |
MIT
|
nlp_100_knocks
|
pythonを用いて、記事中に含まれる「基礎情報」テンプレートのフィールド名と値を抽出し、辞書オブジェクトとして格納せよ。
|
|
import re
import pandas as pd
def remove_stress(dc):
r = re.compile("'+")
return {k: r.sub('', v) for k, v in dc.items()}
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
uk_texts = uk_text.split('\n')
pattern = re.compile('\|(.+?)\s=\s*(.+)')
ans = {}
for line in uk_texts:
r = re.search(pattern, line)
if r:
ans[r[1]] = r[2]
print(remove_stress(ans))
|
code_generation
| 581 |
MIT
|
nlp_100_knocks
|
pythonを用いて、記事中に含まれる「基礎情報」テンプレートのフィールド名と値を抽出し、辞書オブジェクトとして格納する処理時に、テンプレートの値からMediaWikiの強調マークアップ(弱い強調、強調、強い強調のすべて)を除去してテキストに変換せよ。
|
|
import re
import pandas as pd
def remove_stress(dc):
r = re.compile("'+")
return {k: r.sub('', v) for k, v in dc.items()}
def remove_inner_links(dc):
r = re.compile('\[\[(.+\||)(.+?)\]\]')
return {k: r.sub(r'\2', v) for k, v in dc.items()}
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
uk_texts = uk_text.split('\n')
pattern = re.compile('\|(.+?)\s=\s*(.+)')
ans = {}
for line in uk_texts:
r = re.search(pattern, line)
if r:
ans[r[1]] = r[2]
print(remove_inner_links(remove_stress(ans)))
|
code_generation
| 582 |
MIT
|
nlp_100_knocks
|
pythonを用いて、記事中に含まれる「基礎情報」テンプレートのフィールド名と値を抽出し、辞書オブジェクトとして格納し、テンプレートの値からMediaWikiの強調マークアップ(弱い強調、強調、強い強調のすべて)を除去してテキストに変換する処理時に、テンプレートの値からMediaWikiの内部リンクマークアップを除去し、テキストに変換せよ。
|
|
import re
import pandas as pd
def remove_stress(dc):
r = re.compile("'+")
return {k: r.sub('', v) for k, v in dc.items()}
def remove_inner_links(dc):
r = re.compile('\[\[(.+\||)(.+?)\]\]')
return {k: r.sub(r'\2', v) for k, v in dc.items()}
def remove_mk(v):
r1 = re.compile("'+")
r2 = re.compile('\[\[(.+\||)(.+?)\]\]')
r3 = re.compile('\{\{(.+\||)(.+?)\}\}')
r4 = re.compile('<\s*?/*?\s*?br\s*?/*?\s*>')
v = r1.sub('', v)
v = r2.sub(r'\2', v)
v = r3.sub(r'\2', v)
v = r4.sub('', v)
return v
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
uk_texts = uk_text.split('\n')
pattern = re.compile('\|(.+?)\s=\s*(.+)')
ans = {}
for line in uk_texts:
r = re.search(pattern, line)
if r:
ans[r[1]] = r[2]
r = re.compile('\[\[(.+\||)(.+?)\]\]')
ans = {k: r.sub(r'\2', remove_mk(v)) for k, v in ans.items()}
print(remove_inner_links(remove_stress(ans)))
|
code_generation
| 583 |
MIT
|
nlp_100_knocks
|
pythonを用いて、記事中に含まれる「基礎情報」テンプレートのフィールド名と値を抽出し、辞書オブジェクトとして格納し、テンプレートの値からMediaWikiの強調マークアップ(弱い強調、強調、強い強調のすべて)を除去してテキストに変換し、テンプレートの値からMediaWikiの内部リンクマークアップを除去し、テキストに変換する処理時に、テンプレートの値からMediaWikiマークアップを可能な限り除去し、国の基本情報を整形せよ。
|
|
import re
import requests
import pandas as pd
def remove_stress(dc):
r = re.compile("'+")
return {k: r.sub('', v) for k, v in dc.items()}
def remove_inner_links(dc):
r = re.compile('\[\[(.+\||)(.+?)\]\]')
return {k: r.sub(r'\2', v) for k, v in dc.items()}
def remove_mk(v):
r1 = re.compile("'+")
r2 = re.compile('\[\[(.+\||)(.+?)\]\]')
r3 = re.compile('\{\{(.+\||)(.+?)\}\}')
r4 = re.compile('<\s*?/*?\s*?br\s*?/*?\s*>')
v = r1.sub('', v)
v = r2.sub(r'\2', v)
v = r3.sub(r'\2', v)
v = r4.sub('', v)
return v
def get_url(dc):
url_file = dc['国旗画像'].replace(' ', '_')
url = 'https://commons.wikimedia.org/w/api.php?action=query&titles=File:' + url_file + '&prop=imageinfo&iiprop=url&format=json'
data = requests.get(url)
return re.search(r'"url":"(.+?)"', data.text).group(1)
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
uk_text = df.query('title=="イギリス"')['text'].values[0]
uk_texts = uk_text.split('\n')
pattern = re.compile('\|(.+?)\s=\s*(.+)')
ans = {}
for line in uk_texts:
r = re.search(pattern, line)
if r:
ans[r[1]] = r[2]
r = re.compile('\[\[(.+\||)(.+?)\]\]')
ans = {k: r.sub(r'\2', remove_mk(v)) for k, v in ans.items()}
print(get_url(remove_inner_links(remove_stress(ans))))
|
code_generation
| 584 |
MIT
|
nlp_100_knocks
|
pythonを用いて、テンプレートの内容を利用し、国旗画像のURLを取得せよ。
|
|
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
print(blocks[5])
mecab < ch04/neko.txt > ch04/neko.txt.mecab
|
code_generation
| 585 |
MIT
|
nlp_100_knocks
|
pythonを用いて、形態素解析結果(neko.txt.mecab)を読み込むプログラムを実装せよ。ただし、各形態素は表層形(surface)、基本形(base)、品詞(pos)、品詞細分類1(pos1)をキーとするマッピング型に格納し、1文を形態素(マッピング型)のリストとして表現せよ。
|
|
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
def extract_surface(block):
res = list(filter(lambda x: x['pos'] == '動詞', block))
res = [r['surface'] for r in res]
return res
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
ans = [extract_surface(block) for block in blocks]
print(ans[5])
|
code_generation
| 586 |
MIT
|
nlp_100_knocks
|
pythonを用いて、動詞の表層形をすべて抽出せよ。
|
|
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
def extract_base(block):
res = list(filter(lambda x: x['pos'] == '動詞', block))
res = [r['base'] for r in res]
return res
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
ans = [extract_base(block) for block in blocks]
print(ans[5])
|
code_generation
| 587 |
MIT
|
nlp_100_knocks
|
pythonを用いて、動詞の基本形をすべて抽出せよ。
|
|
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
def extract_a_no_b(block):
res = []
for i in range(1, len(block) - 1):
if block[i - 1]['pos'] == '名詞' and block[i]['base'] == 'の' and block[i + 1]['pos'] == '名詞':
res.append(block[i - 1]['surface'] + block[i]['surface'] + block[i + 1]['surface'])
return res
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
ans = [extract_a_no_b(block) for block in blocks]
print(ans)
|
code_generation
| 588 |
MIT
|
nlp_100_knocks
|
pythonを用いて、2つの名詞が「の」で連結されている名詞句を抽出せよ。
|
|
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
def extract_noun_noun(block):
res = []
tmp = []
for b in block:
if b['pos'] == '名詞':
tmp.append(b['surface'])
elif len(tmp) >= 2:
res.append(''.join(tmp))
tmp = []
else:
tmp = []
return res
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
ans = [extract_noun_noun(block) for block in blocks]
print(ans)
|
code_generation
| 589 |
MIT
|
nlp_100_knocks
|
pythonを用いて、文章中に出現する単語とその出現頻度を求め、出現頻度の高い順に並べよ。
|
|
from collections import defaultdict
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
def extract_words(block):
return [b['base'] + '_' + b['pos'] + '_' + b['pos1'] for b in block]
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
words = [extract_words(block) for block in blocks]
d = defaultdict(int)
for word in words:
for w in word:
d[w] += 1
ans = sorted(d.items(), key=lambda x: x[1], reverse=True)
print(ans)
|
code_generation
| 590 |
MIT
|
nlp_100_knocks
|
pythonを用いて、文章中に出現する単語とその出現頻度を求め、出現頻度の高い順に並べよ。
|
|
from collections import defaultdict
import matplotlib.pyplot as plt
import japanize_matplotlib
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
def extract_words(block):
return [b['base'] + '_' + b['pos'] + '_' + b['pos1'] for b in block]
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
words = [extract_words(block) for block in blocks]
d = defaultdict(int)
for word in words:
for w in word:
d[w] += 1
ans = sorted(d.items(), key=lambda x: x[1], reverse=True)[:10]
labels = [a[0] for a in ans]
values = [a[1] for a in ans]
plt.figure(figsize=(15, 8))
plt.barh(labels, values)
plt.savefig('ch04/ans36.png')
|
code_generation
| 591 |
MIT
|
nlp_100_knocks
|
pythonを用いて、出現頻度が高い10語とその出現頻度をグラフ(例えば棒グラフなど)で表示せよ。
|
|
from collections import defaultdict
import matplotlib.pyplot as plt
import japanize_matplotlib
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
def extract_base(block):
return [b['base'] for b in block]
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
words = [extract_base(block) for block in blocks]
words = list(filter(lambda x: '猫' in x, words))
d = defaultdict(int)
for word in words:
for w in word:
if w != '猫':
d[w] += 1
ans = sorted(d.items(), key=lambda x: x[1], reverse=True)[:10]
labels = [a[0] for a in ans]
values = [a[1] for a in ans]
plt.figure(figsize=(8, 8))
plt.barh(labels, values)
plt.savefig('ch04/ans37.png')
|
code_generation
| 592 |
MIT
|
nlp_100_knocks
|
pythonを用いて、「猫」とよく共起する(共起頻度が高い)10語とその出現頻度をグラフ(例えば棒グラフなど)で表示せよ。
|
|
from collections import defaultdict
import matplotlib.pyplot as plt
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
def extract_words(block):
return [b['base'] + '_' + b['pos'] + '_' + b['pos1'] for b in block]
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
words = [extract_words(block) for block in blocks]
d = defaultdict(int)
for word in words:
for w in word:
d[w] += 1
ans = d.values()
plt.figure(figsize=(8, 8))
plt.hist(ans, bins=100)
plt.savefig('ch04/ans38.png')
|
code_generation
| 593 |
MIT
|
nlp_100_knocks
|
pythonを用いて、単語の出現頻度のヒストグラムを描け。ただし、横軸は出現頻度を表し、1から単語の出現頻度の最大値までの線形目盛とする。縦軸はx軸で示される出現頻度となった単語の異なり数(種類数)である。
|
|
import math
from collections import defaultdict
import matplotlib.pyplot as plt
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(lineDict)
def extract_words(block):
return [b['base'] + '_' + b['pos'] + '_' + b['pos1'] for b in block]
filename = 'ch04/neko.txt.mecab'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_mecab(block) for block in blocks]
words = [extract_words(block) for block in blocks]
d = defaultdict(int)
for word in words:
for w in word:
d[w] += 1
ans = sorted(d.items(), key=lambda x: x[1], reverse=True)
ranks = [math.log(r + 1) for r in range(len(ans))]
values = [math.log(a[1]) for a in ans]
plt.figure(figsize=(8, 8))
plt.scatter(ranks, values)
plt.savefig('ch04/ans39.png')
|
code_generation
| 594 |
MIT
|
nlp_100_knocks
|
pythonを用いて、単語の出現頻度順位を横軸、その出現頻度を縦軸として、両対数グラフをプロットせよ。
|
|
class Morph:
def __init__(self, dc):
self.surface = dc['surface']
self.base = dc['base']
self.pos = dc['pos']
self.pos1 = dc['pos1']
def parse_cabocha(block):
res = []
for line in block.split('\n'):
if line == '':
return res
elif line[0] == '*':
continue
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
res.append(Morph(lineDict))
filename = 'ch05/ai.ja.txt.cabocha'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_cabocha(block) for block in blocks]
for m in blocks[2]:
print(vars(m))
|
code_generation
| 595 |
MIT
|
nlp_100_knocks
|
pythonを用いて、形態素を表すクラスMorphを実装せよ。このクラスは表層形(surface)、基本形(base)、品詞(pos)、品詞細分類1(pos1)をメンバ変数に持つこととする。さらに、係り受け解析の結果(ai.ja.txt.parsed)を読み込み、各文をMorphオブジェクトのリストとして表現し、冒頭の説明文の形態素列を表示せよ。
|
|
class Morph:
def __init__(self, dc):
self.surface = dc['surface']
self.base = dc['base']
self.pos = dc['pos']
self.pos1 = dc['pos1']
class Chunk:
def __init__(self, morphs, dst):
self.morphs = morphs # 形態素(Morphオブジェクト)のリスト
self.dst = dst # 係り先文節インデックス番号
self.srcs = [] # 係り元文節インデックス番号のリスト
def parse_cabocha(block):
def check_create_chunk(tmp):
if len(tmp) > 0:
c = Chunk(tmp, dst)
res.append(c)
tmp = []
return tmp
res = []
tmp = []
dst = None
for line in block.split('\n'):
if line == '':
tmp = check_create_chunk(tmp)
elif line[0] == '*':
dst = line.split(' ')[2].rstrip('D')
tmp = check_create_chunk(tmp)
else:
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
tmp.append(Morph(lineDict))
for i, r in enumerate(res):
res[int(r.dst)].srcs.append(i)
return res
filename = 'ch05/ai.ja.txt.cabocha'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_cabocha(block) for block in blocks]
for m in blocks[7]:
print([mo.surface for mo in m.morphs], m.dst, m.srcs)
|
code_generation
| 596 |
MIT
|
nlp_100_knocks
|
pythonを用いて、形態素を表すクラスMorphと文節を表すクラスChunkを実装せよ。このクラスは形態素(Morphオブジェクト)のリスト(morphs)、係り先文節インデックス番号(dst)、係り元文節インデックス番号のリスト(srcs)をメンバ変数に持つこととする。さらに、入力テキストの係り受け解析結果を読み込み、1文をChunkオブジェクトのリストとして表現し、冒頭の説明文の文節の文字列と係り先を表示せよ。本章の残りの問題では、ここで作ったプログラムを活用せよ。
|
|
class Morph:
def __init__(self, dc):
self.surface = dc['surface']
self.base = dc['base']
self.pos = dc['pos']
self.pos1 = dc['pos1']
class Chunk:
def __init__(self, morphs, dst):
self.morphs = morphs # 形態素(Morphオブジェクト)のリスト
self.dst = dst # 係り先文節インデックス番号
self.srcs = [] # 係り元文節インデックス番号のリスト
def parse_cabocha(block):
def check_create_chunk(tmp):
if len(tmp) > 0:
c = Chunk(tmp, dst)
res.append(c)
tmp = []
return tmp
res = []
tmp = []
dst = None
for line in block.split('\n'):
if line == '':
tmp = check_create_chunk(tmp)
elif line[0] == '*':
dst = line.split(' ')[2].rstrip('D')
tmp = check_create_chunk(tmp)
else:
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
tmp.append(Morph(lineDict))
for i, r in enumerate(res):
res[int(r.dst)].srcs.append(i)
return res
filename = 'ch05/ai.ja.txt.cabocha'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_cabocha(block) for block in blocks]
for b in blocks:
for m in b:
if int(m.dst) > -1:
print(''.join([mo.surface if mo.pos != '記号' else '' for mo in m.morphs]),
''.join([mo.surface if mo.pos != '記号' else '' for mo in b[int(m.dst)].morphs]), sep='\t')
|
code_generation
| 597 |
MIT
|
nlp_100_knocks
|
pythonを用いて、係り元の文節と係り先の文節のテキストをタブ区切り形式ですべて抽出せよ。ただし、句読点などの記号は出力しないようにせよ。
|
|
class Morph:
def __init__(self, dc):
self.surface = dc['surface']
self.base = dc['base']
self.pos = dc['pos']
self.pos1 = dc['pos1']
class Chunk:
def __init__(self, morphs, dst):
self.morphs = morphs # 形態素(Morphオブジェクト)のリスト
self.dst = dst # 係り先文節インデックス番号
self.srcs = [] # 係り元文節インデックス番号のリスト
def parse_cabocha(block):
def check_create_chunk(tmp):
if len(tmp) > 0:
c = Chunk(tmp, dst)
res.append(c)
tmp = []
return tmp
res = []
tmp = []
dst = None
for line in block.split('\n'):
if line == '':
tmp = check_create_chunk(tmp)
elif line[0] == '*':
dst = line.split(' ')[2].rstrip('D')
tmp = check_create_chunk(tmp)
else:
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
tmp.append(Morph(lineDict))
for i, r in enumerate(res):
res[int(r.dst)].srcs.append(i)
return res
filename = 'ch05/ai.ja.txt.cabocha'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_cabocha(block) for block in blocks]
for b in blocks:
for m in b:
if int(m.dst) > -1:
pre_text = ''.join([mo.surface if mo.pos != '記号' else '' for mo in m.morphs])
pre_pos = [mo.pos for mo in m.morphs]
post_text = ''.join([mo.surface if mo.pos != '記号' else '' for mo in b[int(m.dst)].morphs])
post_pos = [mo.pos for mo in b[int(m.dst)].morphs]
if '名詞' in pre_pos and '動詞' in post_pos:
print(pre_text, post_text, sep='\t')
|
code_generation
| 598 |
MIT
|
nlp_100_knocks
|
pythonを用いて、名詞を含む文節が、動詞を含む文節に係るとき、これらをタブ区切り形式で抽出せよ。ただし、句読点などの記号は出力しないようにせよ。
|
|
import pydot
class Morph:
def __init__(self, dc):
self.surface = dc['surface']
self.base = dc['base']
self.pos = dc['pos']
self.pos1 = dc['pos1']
class Chunk:
def __init__(self, morphs, dst):
self.morphs = morphs # 形態素(Morphオブジェクト)のリスト
self.dst = dst # 係り先文節インデックス番号
self.srcs = [] # 係り元文節インデックス番号のリスト
def parse_cabocha(block):
def check_create_chunk(tmp):
if len(tmp) > 0:
c = Chunk(tmp, dst)
res.append(c)
tmp = []
return tmp
res = []
tmp = []
dst = None
for line in block.split('\n'):
if line == '':
tmp = check_create_chunk(tmp)
elif line[0] == '*':
dst = line.split(' ')[2].rstrip('D')
tmp = check_create_chunk(tmp)
else:
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1': attr[1]
}
tmp.append(Morph(lineDict))
for i, r in enumerate(res):
res[int(r.dst)].srcs.append(i)
return res
filename = 'ch05/ai.ja.txt.cabocha'
with open(filename, mode='rt', encoding='utf-8') as f:
blocks = f.read().split('EOS\n')
blocks = list(filter(lambda x: x != '', blocks))
blocks = [parse_cabocha(block) for block in blocks]
pairs = []
target = blocks[7]
for m in target:
if int(m.dst) > -1:
pre_text = ''.join([mo.surface if mo.pos != '記号' else '' for mo in m.morphs])
post_text = ''.join([mo.surface if mo.pos != '記号' else '' for mo in target[int(m.dst)].morphs])
pairs.append([pre_text, post_text])
print(pairs)
g = pydot.graph_from_edges(pairs)
g.write_png('ch05/ans44.png', prog='dot')
|
code_generation
| 599 |
MIT
|
nlp_100_knocks
|
pythonを用いて、与えられた文の係り受け木を有向グラフとして可視化せよ。可視化には、Graphviz等を用いるとよい。
|
Subsets and Splits
Python Code Generation
Provides a structured view of code generation tasks specific to a Python-focused course, helping to understand the nature and sequence of the instructions and outputs.
Filtered Code Generation Tasks
The query extracts code generation questions and answers from a specific dataset source, offering structured insights into its contents.
Code Generation Instruction Split
The query processes and splits code generation outputs into separate answers, providing a structured view of potential alternative solutions for each instruction.
Filtered Code Generation Task
The query performs basic filtering and returns formatted data related to code generation tasks, which is helpful but does not provide deep insights into the dataset's underlying structure or patterns.
Code Generation Instructions
The query performs basic filtering to select code generation tasks and organizes them by license, source, and index, providing a simple overview but lacking deeper analytical insight.
Code Generation Instructions
The query performs basic filtering and selects specific columns, providing limited insight into the dataset's structure but not revealing deeper patterns or relationships.
Code Generation Instructions
The query performs basic filtering and selection, organizing code generation tasks by license and source but does not provide deep insights into the data.
^_Call_Call:::^_Call_Call:
The query performs basic filtering and selection, organizing code generation tasks by license, source, and index without revealing deeper insights.
^^^_Call.FromSeconds:^^ withheld^
The query performs basic filtering and ordering of dataset entries, providing a structured view but lacking deeper insights.
_Call^^^^^ serotonin^:^
The query performs basic data retrieval and organization, presenting specific fields in a structured format but without providing significant analytical insights.