首页 > 解决方案 > 如何在文本文件中提取不同的数据子集并将每个子集传递到另一个文本文件中?

问题描述

我的文本文件很少,我需要对子标题数据和该子标题数据的内容进行子集化并传递给另一个文件。

文本文件看起来像这样

Notes 

1. content

2. here also there will be some content till n lines

rule Note 

1. n line content (a) for every section

Add Notes

(a) some content

other Note

1. the rest of file
***Code***
    with open(file,encoding='utf8') as in_file: 
        s = in_file.read() 

        for i, char in enumerate(s): 
            if s[i:i+5] == 'Notes': 
                break      

        for j in range(i,0,-1): 
            if s[j] == '\n': 
                break
        rest_of_file = s[j+1:]

上面的代码从 Notes 的文本文件中提取数据。所以我的预期输出在第一次迭代中看起来像这样,需要传递给另一个文件

Notes 

1. content

2. here also there will be some content till n lines

第二次迭代

rule Note 

1. n line content (a) for every section

第三次迭代

Add Notes

(a) some content

最终迭代

other Note

1. the rest of file

注意:这是一个文件,它的所有子标题都带有模式,但所有文本文件可能并不相同。有些文件可能会丢失注释,有些文件可能会丢失规则注释和添加注释,有些文件可能直接有其他注释,这样可能会发生

我在这里找到的唯一常见模式是注意

任何方法都可以,任何人都可以帮助解决这个问题……请准备好用漂亮的汤

标签: python-3.xtext-processing

解决方案


这样做的方法是

  1. 将所有内容都传递到列表中
  2. 如果注释出现在项目中,则将项目索引放入列表中
  3. 基于索引列表将其与不同的部分分开

示例代码在这里:

如何从python中的列表索引获取列表的子集


推荐阅读