2017-08-02 4 views
0

だから、私は、これらのセクションのセクションとテキストを持っている:Python。セクションごとにテキストを解析する方法は?

​​

そして、どのようにこれらのいずれかのセクションからテキストを取得するには?

+0

可能な複製(https://stackoverflow.com/questions/1059559/split-strings-with-multiple-delimiters) –

+1

読む[のConfigParser]について(HTTPS:/ /docs.python.org/3.6/library/configparser.html) – stovfl

+0

ありがとう@stovfl。 – Rahul

答えて

3
import re 
sections = re.split(r'\[Section\d+\]', text) 

次に、セクションスライスを使用してセクションテキストの1つを取得できます。あなたのケースでは:

section[1] will give section 1. 
+0

これらのいずれか。すべてではない。 – jcommander

+0

@jcommander:編集 – Rahul

+0

も参照してください[configparser](https://docs.python.org/3.6/library/configparser.html)を使用することを検討してください – Rahul

0

示すよう

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'] 
0

、これを試してみてください、このコードは、セクション名でインデックス化順序で各セクションの行の辞書を生成します。

ファイルを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']}) 
[複数の区切り文字で分割ストリングス?]の
+0

UnboundLocalError:割り当て前にローカル変数 'section_name'が参照されています – jcommander

+0

あなたが誤って私はちょうど成功して、もう一度それを実行したので、コード。 –

+0

編集に示すように、コードを簡略化することができます。 –

関連する問題