2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MacのTabでハマった(vscode-python-split)

Last updated at Posted at 2022-04-30

pythonでタブ区切りのデータを取得しようとした時にうまくいかなくてハマったのでメモを残しておく

元データはとある教本(とても勉強になります)に書いてあったらサンプルデータをダウンロードしたもの

sample.txt
# 実は区切りがスペース4個になってしまっています
こんばん(は|わ)$    こんばんは|お疲れ様です
・・・・・

ファイル自体は恐らくWindows向けを想定されていると思います。
それを以下の文で読んでみる

getdata.py
pfile = open('sample.txt','r',encoding='utf_8')
p_lines = pfile.readlines()
pfile.close()
new_lines = []
for line in p_lines:
      # 区切り文字で右から分割
  str = line.rstrip('¥n')
  if (str != ''):
    new_lines.append(str)
  pattern = {}
  for line in new_lines:
      # 区切り文字で分割
      # ¥tはタブ
    ptn,prs = line.split('\t')
    pattern.setdefault('pattern',[]).append(ptn)
    pattern.setdefault('phrases',[]).append(prs)
    print(pattern)

そうすると以下のようなエラーとなる

Traceback (most recent call last):
  File "**/practice.py", line 17, in <module>
    ptn,prs = line.split('\t')
ValueError: not enough values to unpack (expected 2, got 1)

どうやらタブで分割できてないようである
そのことに気が付かずVscod上でテキストファイルを新しく作ってMacのキーボード上の[tab]を作ったり、スペースの数を変えてみたりが解決しなかった
(マシンガン的解決方法、、、)

解決策

Vscodeでは普通にtabボタンを押すとスペースとして入力されてしまう
以下のようにしてtabを打てるようにする
①コマンドパレット(ctrl + shift + p) で「open keyboard Shortcuts」を開く

image.png

②以下のように入力する ※割り当てるボタンは任意

// 既定値を上書きするには、このファイル内にキー バインドを挿入します
[
  {
    "key": "ctrl+t",
    "command": "type",
    "args": { "text": "\t" },
    "when": "editorTextFocus"
  }
]

これでVScode上でタブを入力することができた
テキストファイルのスーペースを全てタブに置き換えて完了しました。

追記

タブ以外にも「¥」も曲者だった
Windowsだと正規表現などで使う「\」(バックスラッシュ)が「¥」(円マーク)になる
そのためWindows用の教本を読む時には「¥」を「\」に読み替えないといけない
※全てではない
読み替え例
文字の先頭が何らかの数字であるものをマッチさせる:「^¥d」 ⇨ 「^\d」

参考サイト
https://kotsukotsu.work/tech/2020-10-15-visual-studio-code-%E3%81%A7%E3%82%BF%E3%83%96%E3%82%92%E5%85%A5%E5%8A%9B%E3%81%99%E3%82%8B/

2
3
2

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?