2015-08-24 31 views
2

文件更好的办法我有以下类型的文件:来划分它有单独的位置的标记在Python

--- part0 --- 
some 
strings 
--- part1 --- 
some other 
strings 
--- part2 --- 
... 

我想获得的文件以Python列表的任何部分:

x = get_part_of_file(part=0) 
print x # => should print ['some', 'strings'] 
x = get_part_of_file(part=1) 
print x # => should print ['some other', 'strings'] 

所以,我的问题是什么,是落实上述使用get_part_of_file方法最简单的方法。

我(丑)解决方案是象下面这样:

def get_part_of_file(part, separate_str="part"): 
    def does_match_to_separate(line): 
     return re.compile("{}.*{}".format(separate_str, part)).match(line) 
    def get_first_line_num_appearing_separate_str(lines): 
     return len(list(end_of_loop() if does_match_to_separate(line, part) else line for line in lines)) 

    with open("my_file.txt") as f: 
     lines = f.readlines() 

    # get first line number of the required part 
    first_line_num = get_first_line_num_appearing_separate_str(part) 
    # get last line number of the required part 
    last_line_num = get_first_line_num_appearing_separate_str(part + 1) - 1 
    return lines[first_line_num:last_line_num] 

回答

2

你可以使用正则表达式来解析字符串。看下面这个例子在这里和尝试上regex101

--- part(?P<part_number>\d+) ---\s(?P<part_value>[\w\s]*) 

这分析给定的字符串转换成以下几组:

  • MATCH 1 PART_NUMBER [8-9] 0 part_value [14-27 ]
  • MATCH 2 PART_NUMBER [35-36] 1 part_value [41-60] some other strings

现在,在Python中,你不能让所有的组与

import re 
parts = re.finditer(your_regex_pattern, text) 

for p in parts: 
    print("Part %s: %s" % (p.group('part_number'), p.group('part_value')) 
    # or return the element with the part-number you want. 

你可以运行到是唯一的问题,此刻正则表达式模式并不只包括个字符,空格和换行\w\s。如果零件的值中还有其他字符,则必须扩展该模式以匹配更多字符。

1

使用re.split你可以写类似

>>> input_file = open('input', 'r') 
>>> content = input_file.read() 
>>> content_parts = re.split('.+?part\d+.+?\n', content) 

>>> content_parts 
['', 'some\nstrings\n', 'some other\nstrings\n', ''] 

>>> [ part.split('\n') for part in content_parts if part ] 
[['some', 'strings', ''], ['some other', 'strings', '']] 
相关问题