だから、私は、これらのセクションのセクションとテキストを持っている:Python。セクションごとにテキストを解析する方法は?
そして、どのようにこれらのいずれかのセクションからテキストを取得するには?
だから、私は、これらのセクションのセクションとテキストを持っている:Python。セクションごとにテキストを解析する方法は?
そして、どのようにこれらのいずれかのセクションからテキストを取得するには?
import re
sections = re.split(r'\[Section\d+\]', text)
次に、セクションスライスを使用してセクションテキストの1つを取得できます。あなたのケースでは:
section[1] will give section 1.
これらのいずれか。すべてではない。 – jcommander
@jcommander:編集 – Rahul
も参照してください[configparser](https://docs.python.org/3.6/library/configparser.html)を使用することを検討してください – Rahul
示すよう
text="""[Section1]
Some weired text in section 1
[Section2]
Some text in section 2
Some text
text"""
print text.split('\n\n')
>>>['[Section1]\nSome weired text in section 1', '[Section2]\nSome text in section 2\nSome text\ntext']
、これを試してみてください、このコードは、セクション名でインデックス化順序で各セクションの行の辞書を生成します。
ファイルを1行ずつ読み込みます。セクションヘッダーを認識すると、セクションヘッダーに名前が記録されます。後続の行を読むと、次のヘッダーを読み取るまで、その名前の下にリストとしてsections
に保存されます。
ラインエンドを必要としない場合は、append
ステートメントでそれらを取り除きます。
>>> import re
>>> patt = re.compile(r'^\s*\[\s*(section\d+)\s*\]\s*$', re.I)
>>> sections = {}
>>> with open('to_chew.txt') as to_chew:
... while True:
... line = to_chew.readline()
... if line:
... m = patt.match(line)
... if m:
... section_name = m.groups()[0]
... sections[section_name] = []
... else:
... sections[section_name].append(line)
... else:
... break
...
>>> sections
{'Section2': ['Some text in section 2\n', 'Some text\n', 'text'], 'Section1': ['Some weired text in section 1\n', '\n']}
編集:単純化したコード。
>>> import re
>>> patt = re.compile(r'^\s*\[\s*(section\d+)\s*\]\s*$', re.I)
>>> sections = defaultdict(list)
>>> with open('to_chew.txt') as to_chew:
... for line in to_chew:
... m = patt.match(line)
... if m:
... section_name = m.groups()[0]
... else:
... sections[section_name].append(line)
...
>>> sections
defaultdict(<class 'list'>, {'Section1': ['Some weired text in section 1\n', '\n'], 'Section2': ['Some text in section 2\n', 'Some text\n', 'text']})
[複数の区切り文字で分割ストリングス?]の
UnboundLocalError:割り当て前にローカル変数 'section_name'が参照されています – jcommander
あなたが誤って私はちょうど成功して、もう一度それを実行したので、コード。 –
編集に示すように、コードを簡略化することができます。 –
可能な複製(https://stackoverflow.com/questions/1059559/split-strings-with-multiple-delimiters) –
読む[のConfigParser]について(HTTPS:/ /docs.python.org/3.6/library/configparser.html) – stovfl
ありがとう@stovfl。 – Rahul