正規表現の宣言について助けが必要です。入力は次のようになります:
this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.
and there are many other lines in the txt files
with<[3> such tags </[3>
必要な出力は次のとおりです。
this is a paragraph with in between and then there are cases ... where the number ranges from 1-100.
and there are many other lines in the txt files
with such tags
私はこれを試しました:
#!/usr/bin/python
import os, sys, re, glob
for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
for line in reader:
line2 = line.replace('<[1> ', '')
line = line2.replace('</[1> ', '')
line2 = line.replace('<[1>', '')
line = line2.replace('</[1>', '')
print line
これも試してみました (ただし、間違った正規表現構文を使用しているようです):
line2 = line.replace('<[*> ', '')
line = line2.replace('</[*> ', '')
line2 = line.replace('<[*>', '')
line = line2.replace('</[*>', '')
replace
1 から 99 までをハードコードしたくありません。
ベストアンサー1
このテスト済みのスニペットでそれが実現できるはずです:
import re
line = re.sub(r"</?\[\d+>", "", line)
編集:仕組みを説明するコメント付きバージョンは次のとおりです:
line = re.sub(r"""
(?x) # Use free-spacing mode.
< # Match a literal '<'
/? # Optionally match a '/'
\[ # Match a literal '['
\d+ # Match one or more digits
> # Match a literal '>'
""", "", line)
正規表現は楽しいです!しかし、1、2 時間かけて基礎を勉強することを強くお勧めします。まず、どの文字が特別なのかを学ぶ必要があります。つまり、エスケープする必要がある「メタ文字」 (つまり、先頭にバックスラッシュを配置します。文字クラスの内側と外側ではルールが異なります) です。次の場所に優れたオンライン チュートリアルがあります。正規表現そこに費やす時間は何倍にもなって報われます。正規表現を楽しんでください!