回答
import re
sections = re.split(r'\[Section\d+\]', text)
然后,您可以使用列表切片获得一个节文本。你的情况:
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']
如图所示,该代码生成每个部分中的线的字典,以便由部分名称索引。
它通过逐行读取文件。当它识别出一个节头时,它会记下这个名字。由于它读取后续行,直到它读取下一个标题,它将它们保存在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
我怀疑你错误地转录了因为我只是再次运行它,并取得成功。 –
代码可以简化,如编辑所示。 –
- 1. Python文本解析&分裂
- 2. 在Python中解析MIME正文部分
- 3. 解析文件部分在python
- 4. Python的解析文本文件的仅特定部分
- 5. 如何按行解析文件并拆分文本
- 6. 如何解析部分HTML?
- 7. Python的解析文本和组成不同的部分
- 8. Python解析:lxml只能得到标记文本的一部分
- 9. 解析部分
- 10. 解析部分
- 11. Python的 - 解析文本
- 12. 用Python解析文本
- 13. python解析xml文本
- 14. python中的文本解析
- 15. 在python中解析txt文件很难按分隔符分割
- 16. 用Python解析XML忽略部分
- 17. 的Python块文本分析
- 18. Python NLTK解析标签文本:如何检索标签文本
- 19. 如何解析文本
- 20. 如何解析文本
- 21. 如何解析文本
- 22. 解析XML部分
- 23. 如何解析部分日期
- 24. 如何用NSURLconnection解析部分xml?
- 25. 如何解析多部分HttpWebResponse
- 26. PERL:按行文本解析脚本行
- 27. 使用Python解析文本文件
- 28. 解析文本文件以CSV在python
- 29. 用标签解析Python文本文件
- 30. 解析文本文件(Python)的
[与多个分隔符分割字符串?]的可能的复制(https://stackoverflow.com/questions/1059559/split-strings-with-multiple-delimiters) –
阅读有关[configparser(HTTPS:/ /docs.python.org/3.6/library/configparser.html) – stovfl
谢谢@stovfl。 – Rahul