如何从多个文件夹和文件中读取特定段落

时间:2019-03-05 22:22:15

标签: python

我有一个列表,其中包含要打开的目录和文件名,从中读取一个段落并将该段落保存到列表中。

问题是我不知道如何从文件中“过滤”该段落并将其插入到我的列表中。

到目前为止我的代码。

rr = []
file_list = [f for f in iglob('**/README.md', recursive=True) if os.path.isfile(f)]
for f in file_list:
  with open(f,'rt') as fl:
    lines = fl.read()
    rr.append(lines)
  print(rr)

我要读取的文件格式。段落开头和新段落之间的文本是我要查找的

There is text above this paragraph
## Required reading
    * line
    * line
    * line
     /n
### Supplementary reading
There is text bellow this paragraph

运行代码时,可以按预期从文件中获取所有行。

2 个答案:

答案 0 :(得分:1)

您需要学习导入文本的结构。段落如何分隔?看起来像'\ n \ n',可以在'\ n \ n'上拆分文本文件并返回所需段落的索引吗?

text = 'paragraph one text\n\nparagraph two text\n\nparagraph three text'.split('\n\n')[1]
print(text)
>>> 'paragraph two text'

另一个选项,就像其他人提到的那样,是正则表达式(又称RegEx),您可以使用

导入
import re

RegEx用于查找文本中的图案。

转到https://pythex.org/并获取其中一个文档的样本,然后尝试查找与您要查找的段落相匹配的模式。

在此处了解有关RegEx的更多信息 https://regexone.com/references/python

答案 1 :(得分:0)

解决了我的字符串切片问题。

基本上,我只扫描每行以查找开始字符串和结束字符串,然后从中取出行。然后将这些行添加到列表中并写入文件中。

for f in file_list:
        with open(f, 'rt') as fl:
            lines = fl.read()
            lines = lines[lines.find('## Required reading'):lines.find('## Supplementary reading')]
            lines = lines[lines.find('## Required reading'):lines.find('### Supplementary reading')]
            lines = lines[lines.find('## Required reading'):lines.find('## Required reading paragraph')]
            rr.append(lines)

但是我的列表和文件中仍然有“ ##必读”,因此我运行了第二种读/写方法。

def removeHashTag():
    global line
    f = open("required_reading.md", "r")
    lines = f.readlines()
    f.close()
    f = open("required_reading.md", "w")
    for line in lines:
        if line != "## Required reading" + "\n":
            f.write(line)
    f.close()
removeHashTag()
相关问题