keep-loving-pythonのブログ

Pythonを愛し続けたいです(Pythonが流行っている限りですが。。。)

Pythonでのwhitespaceとは、具体的に何か?

ものすごく厳密に追及するわけではありませんが。。。

リファレンスには、明記されていないと思います。

stringモジュールにwhitespaceというのがあります。

一致するかどうかは不明ですが、それは、すべて含んでいるようです。

検証したコード

import string
print(repr(string.whitespace))
# ' \t\n\r\x0b\x0c'

a = ' \t\n\r\x0b\x0c___uuu___ \t\n\r\x0b\x0c'
print(repr(a))
# ' \t\n\r\x0b\x0c___uuu___ \t\n\r\x0b\x0c'
print(repr(a.strip()))
# '___uuu___'



回答

' \t\n\r\x0b\x0c' は、含まれている感じ。whitespaceを除外するstripで除外されたから。

解決策。Pythonがしれっとプロンプトに戻る2。

はじめて現場をおさえました!!!

ちなみに

しれっとプロンプトに戻ったコードは

import copy

def deep_copy(obj):
    if isinstance(obj, list):
        print("list")
        return [deep_copy(item) for item in obj]
    elif isinstance(obj, dict):
        print("dict")
        return {key: deep_copy(value) for key, value in obj.items()}
    else:
        print("others")
        return copy.copy(obj)

a = {"aaa":999,"bbb":777}
b = [1,2,3,4]
c = 200

a_copy = deep_copy(a)
a_copy_normal = copy.copy(a)
a["bbb"] = 33333
print(a,a_copy,a_copy_normal)

b_copy = deep_copy(b)
b_copy_normal = copy.copy(b)
b[0] = 33333
print(b,b_copy,b_copy_normal)

c_copy = deep_copy(c)
c_copy_normal = copy.copy(c)
c = 33333
print(c,c_copy,c_copy_normal)

解決策

メモリ!!

解決策(続編)。re.error: bad escape \s at position 0(多少、意味のある解読付き)

エラー

環境

windows10
pythonPython 3.10.11

エラー

re.error: bad escape \s at position 0

解決策

rをつけるとか、"\"を増やすとか。。。

検討したソース

import re

print(help(re.sub))
a = 'xyz_opqrstu_\s\t\c'
b = 'dummy'

print("===== yen 1 ====")
print("r-nashi-")
print("moto:",a)
# b = re.sub('\s','\s',a)
# re.error: bad escape \s at position 0
print(" ato:",b)

print("r-ari-")
print("moto:",a)
#b = re.sub('\s',r'\s',a)
#re.error: bad escape \s at position 0
print(" ato:",b)

print("===== yen 2 ====")
print("r-nashi-")
print("moto:",a)
#b = re.sub('\s','\\s',a)
#re.error: bad escape \s at position 0
print(" ato:",b)

print("r-ari-")
print("moto:",a)
b = re.sub('\s',r'\\s',a)
print(" ato:",b)
#moto: xyz_opqrstu_\s    \c
#ato: xyz_opqrstu_\s\s\c


print("===== yen 3 ====")
print("r-nashi-")
print("moto:",a)
b = re.sub('\s','\\\s',a)
print(" ato:",b)
#moto: xyz_opqrstu_\s    \c
# ato: xyz_opqrstu_\s\s\c


print("r-ari-")
print("moto:",a)
# b = re.sub('\s',r'\\\s',a)
# re.error: bad escape \s at position 2
print(" ato:",b)

↑どんどん"\"を足してみて下さい。3個周期???。

実行結果(すみません、print文が適切でないので、、、↑のコードのほうをみて欲しいです。)

===== yen 1 ====
r-nashi-
moto: xyz_opqrstu_\s    \c
 ato: dummy
r-ari-
moto: xyz_opqrstu_\s    \c
 ato: dummy
===== yen 2 ====
r-nashi-
moto: xyz_opqrstu_\s    \c
 ato: dummy
r-ari-
moto: xyz_opqrstu_\s    \c
 ato: xyz_opqrstu_\s\s\c
===== yen 3 ====
r-nashi-
moto: xyz_opqrstu_\s    \c
 ato: xyz_opqrstu_\s\s\c
r-ari-
moto: xyz_opqrstu_\s    \c
 ato: xyz_opqrstu_\s\s\c

解説

どうも、、、re.subの2つ目の引数は、
①最初に文字列としてエスケープ処理される。
②次に、その処理後の文字列の"\"付きの部分がエスケープできるかを判定する。で、"\s"とかは知りません!となる。
なぜか、できないならできないで良いという処理にならない!!!
上記の②の処理が、普通、理解不能だと思う、実装依存というか、実装都合なんでしょう!!!

補足2023/10/08

b = re.sub('\s',r'\\s',a)が良い姿 (python3.7でも同様のはず)

解決策。SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated \uXXXX escape

エラー

環境

Python 3.10.11 windows10

エラーの内容

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated \uXXXX escape

エラー全文

  File "C:\_pythonJISYUTORE\usertest\pre_test00.py", line 1
    a = "C:\_pythonJISYUTORE\usertest"
                                      ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated \uXXXX escape

エラーが発生するソース

a = "C:\_pythonJISYUTORE\usertest"

解決策

目的にもよりますが、、、
rをつける。

a = r"C:\_pythonJISYUTORE\usertest"

説明

"\u" が特別な意味があるということ。

類似問題

ソース:

a = "C:\_pythonJISYUTORE\aaausertest\xzz"

エラー

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 31-32: truncated \xXX escape

対策: 同じくr をつける

解説: "\x"が特別な意味がありますということ。

解決策。RuntimeError: expected scalar type Long but found Int(★多少役立つかも。。。)

エラー

環境

windows10
python3.7

モジュールのバージョン

torch 1.9.0+cpu
transformers 4.30.2

エラー

RuntimeError: expected scalar type Long but found Int

エラー詳細

Traceback (most recent call last):
  File "bert_ner5.py", line 235, in <module>
    attention_mask=b_input_mask, labels=b_labels)
  File "C:\Users\XYZZZ\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\XYZZZ\AppData\Local\Programs\Python\Python37\lib\site-packages\transformers\models\bert\modeling_bert.py", line 1778, in forward
    loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  File "C:\Users\XYZZZ\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\XYZZZ\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\loss.py", line 1121, in forward
    ignore_index=self.ignore_index, reduction=self.reduction)
  File "C:\Users\XYZZZ\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\functional.py", line 2824, in cross_entropy
    return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: expected scalar type Long but found Int

予備元の関数

        outputs = model(b_input_ids, token_type_ids=None,
                        attention_mask=b_input_mask, labels=b_labels)

解決策

Long(64ビット)でなく、Int(32ビット)が入力されていることが原因。

以下のように明示的に変換して対処しても良い。

tr_inputs = torch.tensor(tr_inputs).to(torch.int64)

できるだけ、上流で、longになるように改修するのが良いと思う。

なぜこのようなことが起きるのか(留意点)

動作実績のあるコード(GitHubや記事で公開されているコード)で、このような現象が出る理由: GPUで動作するものをCPU環境で動作させていませんか?(このあたりでNGになる可能性があるのでは?これ、想像ですけど。。。)

解決のノウハウ

可能性高:

  • GPU/CPUの差で、そもそもの型の問題が発症 (<--勘、ですが。)

可能性低:

  • モジュールのバージョン

コメント

コメントなどあればお願いします

解決策。AttributeError: 'ByteLevelBPETokenizer' object has no attribute 'save_model'

エラー

環境

windows10
python3.7

エラーの内容

AttributeError: 'ByteLevelBPETokenizer' object has no attribute 'save_model'

詳細

Traceback (most recent call last):
  File "_espe00_bert.py", line 25, in <module>
    tokenizer.save_model(".", "esperberto")
AttributeError: 'ByteLevelBPETokenizer' object has no attribute 'save_model'

モジュールのバージョン

tokenizers 0.7.0

解決策

python -m pip install tokenizers==0.8.0rc1

↑たぶん、これ以上ならOK?

コメント

なんでもコメント頂けると参考になりまーす。

今更ーー! Google Colabでは、「!cd xxxx」でディレクトリ移動できない。

元々のJupyterコマンドとかぶるかららしいです。

Google Colabは、Jupyterコマンドを継承しています。Jupyterでは、現在の作業ディレクトリを変更する場合は、組み込みのマジックコマンド%cdを使用します。

上記は、いかの記載を引用。

github.com

だから、、、

  • びっくりマークをはずす。
  • または、%をつける。