我有一个文本文件,它包含教科书中的解决方案,我试图将每个解决方案分割成它自己的文本文件,在搜索完之后,我似乎找不到一个优雅的解决方案。
每个解决方案都以问题号(如*1-3;或*4-2; )作为前缀。
我可以在文件中读取,并将每一行存储在列表中,但实际上我在处理按标题拆分的列表时遇到了困难。
这里有一个巴斯特箱,里面有一些直接来自.txt:http://pastebin.com/ntSXLn72的解决方案
谢谢!
发布于 2013-11-06 19:47:51
#!/usr/bin/python
import re
file_name = "" # put the txt file you're working on
new_header = None
for line in open(file_name,"r").readlines():
if re.search("^[*][0-9]+[-][0-9]+[;]", line):
if new_header:
new_header.close()
new_header = open("%s_section:%s" % (file_name, line), "w")
if new_header:
new_header.write(line)
if new_header:
new_header.close 发布于 2013-11-06 19:37:17
使用re.split
import re
with open('text.txt') as f:
text = f.read()
solutions = re.split('\*[0-9]\-[0-9];',text)该正则表达式将查找*<any number>-<any number>;,并将全文分割为任何匹配的内容。您可能需要对空成员进行一些清理。
https://stackoverflow.com/questions/19820990
复制相似问题