繁体   English   中英

如何将txt文件拆分为多个文件,但不包含具有某些内容的行

[英]How to split a txt file into multiple files excluding lines with certain content

我有一个大的.txt文件,我想将其拆分为多个较小的.txt文件,因此在每个较小的.txt文件中都有可读的段落。

但是,我想做的是将源文件的某些部分排除在较小的文件之外。 (即,如果行不是以<p>开头,则不要写入文件)。

这是我的代码-可以正常工作,但它会生成一些我不需要的文件:

import mmap
import re

filenumber = 0

out_file = None

with open('main.txt') as x:
    for line in x:
        if line.strip() == '<p>':
             filenumber += 1
            out_file = open('narrative%03d.txt' % filenumber, 'w')
        elif line.strip().startswith('</p>') and out_file:
            out_file.close()
            out_file = None
        elif out_file:
            out_file.write(line)
if out_file:
    out_file.close()

我想做的是找出一种说法-运行代码,但是如果一行开头不是以<p>开头,则什么都不做,然后继续其余的代码。

任何帮助将不胜感激! 如果我没有提供足够的信息,请告诉我!

由于源文件包含html标记,因此向我展示源文件的最简单方法是提供指向该文件的链接:

https://archive.org/stream/warandpeace030164mbp/warandpeace030164mbp_djvu.txt

查看源代码以查看我不想包含的部分。

我只想要书中的段落-

他的女儿He * lene公主在椅子之间经过,轻轻地举起衣服的褶皱,美丽的容颜上散发出灿烂的笑容。 当皮埃尔经过他时,皮埃尔用狂喜的,几乎是恐惧的眼睛注视着她。

“非常可爱。”安德鲁王子说。

我不希望文档的开头包含所有html和章节列表等。

对于您提供的链接,整个文本都包含在一个巨大的<pre>...</pre>块中。 这样,您可以使用BeautifulSoup轻松提取它。

首先使用诸如requests东西抓取html,使用BeautifulSoup提取包含单个pre的文本,然后基于双换行符将文本拆分并删除所有空条目:

from bs4 import BeautifulSoup
import requests

html = requests.get('https://archive.org/stream/warandpeace030164mbp/warandpeace030164mbp_djvu.txt')
soup = BeautifulSoup(html.text, "lxml")
war_and_peace = soup.pre.get_text()

paragraphs = war_and_peace.split('\n\n')
paragraphs[:] = [p for p in paragraphs if len(p)]       # Remove empty entries

print paragraphs[671]

结果将是一个段落列表。 该脚本将显示以下内容:

His daughter, Princess He*lene, passed be- 
tween the chairs, lightly holding up the folds 
of her dress, and the smile shone still more 
radiantly on her beautiful face. Pierre gazed 
at her with rapturous, almost frightened, eyes 
as she passed him.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM