0
0

More than 1 year has passed since last update.

Grasshopper で Shift JIS 形式のテキストデータを読み込む

Last updated at Posted at 2022-01-15

はじめに

Grasshopper の ReadFileコンポーネント でCSVデータを読み込んだら文字化けしてしまった。Shift JIS のテキストデータはエンコード指定が必要と教えていただいたのでやってみた。(kanano さんありがとうございます!)
image.png

Pythonで文字コードをゴニョゴニョ

GhPython Script コンポーネントのインプットを FileName アウトプットを txt に変更

image.png

「Python 文字コード」で検索すると山ほど情報が出てくるんだけど、GhPythonではうまく動かないものが多くいが意外と苦労した。最終的に成功したのはこちら

txt = []
with open(FileName) as f:
    for line in f:
        txt.append(unicode(line, 'shift-jis'))

変換成功!

image.png

C#でもやってみた

このサイトを参考にC# Script コンポーネントでも作ってみた
Shift_Jisで保存されたファイルを読み込んでUTF-8に変換する

using ディレクティブに追記

image.png

using System.Text;
using System.IO;

RunScriptの中に追記

image.png

    Encoding srcEncoding = Encoding.GetEncoding("shift_jis");
    Encoding dstEncoding = Encoding.UTF8;
    using (var reader = new StreamReader(FileName, srcEncoding))
    {
      string line = null;
      var strList = new List<string>();
      while ((line = reader.ReadLine()) != null)
      {
        String convertedLine =
          dstEncoding.GetString(
          System.Text.Encoding.Convert(
          srcEncoding,
          dstEncoding,
          srcEncoding.GetBytes(line)));

        strList.Add(convertedLine);
      }
      txt = strList;
    }

image.png

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0