2017-08-02 57 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) 

然后,您可以使用列表切片获得一个节文本。你的情况:

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

如图所示,该代码生成每个部分中的线的字典,以便由部分名称索引。

它通过逐行读取文件。当它识别出一个节头时,它会记下这个名字。由于它读取后续行,直到它读取下一个标题,它将它们保存在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

代码可以简化,如编辑所示。 –