1
0

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 3 years have passed since last update.

Pythonでソースコードから日本語を含む1行コメントを削除する

Last updated at Posted at 2020-10-03

この記事ではPython3を使っています。

コード

test.py
import re

# 改行コード
EOL = '\n'
# ASCIIパターン
p_ac = '[!-~\\s]'
# 日本語(ASCII以外)パターン
p_jp = '([^!-~\\s]|[ ])'

# 1行コメントパターン
p_com = '//'
# p_com = '#'

# pattern 全体
pattern = f'[ ]*{p_com}({p_ac}*{p_jp}+)+{p_ac}*$'

# 置換したい文字列
s = '''1 aaa
2 bbb // あaいiうuえeおo
3  // kaかkiきkuくkeけkoこ
4    // いいい
5 // uuu
6 print (aaa)   // aaaを表示
7 print (ccc)   // print ccc
8
[EOD]'''

# 置換前
print (s)
print ('----------------------')

n = ''
# 一行ごとに分割
ary = s.split(EOL)

# 置換処理
for l in ary:
    # 対象削除
    r = re.sub(pattern, '', l)
    n += r + EOL

# 置換後
print (n)

出力

1 aaa
2 bbb // あaいiうuえeおo
3  // kaかkiきkuくkeけkoこ
4    // いいい
5 // uuu
6 print (aaa)   // aaaを表示
7 print (ccc)   // print ccc
8
[EOD]
----------------------
1 aaa
2 bbb
3
4
5 // uuu
6 print (aaa)
7 print (ccc)   // print ccc
8
[EOD]
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?