【问题标题】:print first paragraph in python在python中打印第一段
【发布时间】:2016-04-06 21:26:17
【问题描述】:

我有一本书的文本文件,我需要打印每个部分的第一段。我想如果我在 \n\n 和 \n 之间找到一个文本,我就能找到我的答案。这是我的代码,它没有用。你能告诉我我哪里错了吗?

lines = [line.rstrip('\n') for line in open('G:\\aa.txt')]

check = -1
first = 0
last = 0

for i in range(len(lines)):
    if lines[i] == "": 
            if lines[i+1]=="":
                check = 1
                first = i +2
    if i+2< len(lines):
        if lines[i+2] == "" and check == 1:
            last = i+2
while (first < last):
    print(lines[first])
    first = first + 1

我还在stackoverflow中找到了一个代码,我也试过了,但它只是打印了一个空数组。

f = open("G:\\aa.txt").readlines()
flag=False
for line in f:
        if line.startswith('\n\n'):
            flag=False
        if flag:
            print(line)
        elif line.strip().endswith('\n'):
            flag=True

我在下面分享了本书的一个示例部分。

大地

有一大片令人着迷的人类兴趣领域,就在我们的门外,到目前为止还很少有人探索。这是动物智能的领域。

在研究世界上的野生动物的各种兴趣中,没有什么比研究它们的思想、道德以及它们作为心理过程的结果所采取的行为更重要的了。

野生动物的性情和个性

我在这里要做的是,找到大写的行,并将它们全部放入一个数组中。然后,使用 index 方法,通过比较我创建的这个数组的这些元素的索引,找到每个部分的第一段和最后一段。

输出应该是这样的:

有一大片令人着迷的人类兴趣领域,就在我们的门外,到目前为止还很少有人探索。这是动物智能的领域。

我在这里要做的是,找到大写的行,并将它们全部放入一个数组中。然后,使用 index 方法,通过比较我创建的这个数组的这些元素的索引,找到每个部分的第一段和最后一段。

【问题讨论】:

  • 您可以按原样添加实际输入和预期输出吗?

标签: python text paragraph


【解决方案1】:

如果你想对部分进行分组,你可以使用itertools.groupby,使用空行作为分隔符:

from itertools import groupby
with open("in.txt") as f:
    for k, sec in groupby(f,key=lambda x: bool(x.strip())):
        if k:
            print(list(sec))

使用更多的 itertools foo 我们可以得到使用大写标题作为分隔符的部分:

from itertools import groupby, takewhile

with open("in.txt") as f:
    grps = groupby(f,key=lambda x: x.isupper())
    for k, sec in grps:
        # if we hit a title line
        if k: 
            # pull all paragraphs
            v = next(grps)[1]
            # skip two empty lines after title
            next(v,""), next(v,"")

            # take all lines up to next empty line/second paragraph
            print(list(takewhile(lambda x: bool(x.strip()), v)))

这会给你:

['There is a vast field of fascinating human interest, lying only just outside our doors, which as yet has been but little explored. It is the Field of Animal Intelligence.\n']
['What I am trying to do here is, find the uppercase lines, and put them all in an array. Then, using the index method, I will find the first and last paragraphs of each section by comparing the indexes of these elements of this array I created.']

每个部分的开头都有一个全大写的标题,所以一旦我们知道有两个空行然后第一段和模式重复。

将其分解为使用循环:

from itertools import groupby  
from itertools import groupby
def parse_sec(bk):
    with open(bk) as f:
        grps = groupby(f, key=lambda x: bool(x.isupper()))
        for k, sec in grps:
            if k:
                print("First paragraph from section titled :{}".format(next(sec).rstrip()))
                v = next(grps)[1]
                next(v, ""),next(v,"")
                for line in v:
                    if not line.strip():
                        break
                    print(line)

对于您的文字:

In [11]: cat -E in.txt

THE LAY OF THE LAND$
$
$
There is a vast field of fascinating human interest, lying only just outside our doors, which as yet has been but little explored. It is the Field of Animal Intelligence.$
$
Of all the kinds of interest attaching to the study of the world's wild animals, there are none that surpass the study of their minds, their morals, and the acts that they perform as the results of their mental processes.$
$
$
WILD ANIMAL TEMPERAMENT & INDIVIDUALITY$
$
$
What I am trying to do here is, find the uppercase lines, and put them all in an array. Then, using the index method, I will find the first and last paragraphs of each section by comparing the indexes of these elements of this array I created.

美元符号是新行,输出是:

In [12]: parse_sec("in.txt")
First paragraph from section titled :THE LAY OF THE LAND
There is a vast field of fascinating human interest, lying only just outside our doors, which as yet has been but little explored. It is the Field of Animal Intelligence.

First paragraph from section titled :WILD ANIMAL TEMPERAMENT & INDIVIDUALITY
What I am trying to do here is, find the uppercase lines, and put them all in an array. Then, using the index method, I will find the first and last paragraphs of each section by comparing the indexes of these elements of this array I created.

【讨论】:

  • 这很酷,我可以使用此代码查看每个部分..但我只想查看它们的第一段..如何提取?
  • @TuğcanDemir,你到底想从你的问题中得到什么?
  • 您仍然可以使用 Padraic 的答案,只需删除仅包含一行的任何组。
  • 非常感谢!但是仍然存在一些问题,因为当我使用此代码时,我再次看到了每个部分的所有段落。它应该是标题和第一段之间的 2 个空行,我无法控制它。我不能在上面的问题中添加 2 个空行,网站不允许:/
  • @TuğcanDemir,您只需再次拨打next(v) 即可跳过第二个空行
【解决方案2】:

总是有正则表达式....

import re
with open("in.txt", "r") as fi:
    data = fi.read()
paras = re.findall(r"""
                   [IVXLCDM]+\n\n   # Line of Roman numeral characters
                   [^a-z]+\n\n      # Line without lower case characters
                   (.*?)\n          # First paragraph line
                   """, data, re.VERBOSE)
print "\n\n".join(paras)

【讨论】:

  • 这个正在成长的模具:“有些人,当遇到问题时,会想'我知道,我会使用正则表达式。' Now they have two problems。” [IV]+ 嗯?
  • 如何打印第一段而不是第一行?
  • 所以,我也找到了使用您的代码的方法..非常感谢 :)
【解决方案3】:

逐行查看找到的代码。

f = open("G:\\aa.txt").readlines()
flag=False
for line in f:
        if line.startswith('\n\n'):
            flag=True
        if flag:
            print(line)
        elif line.strip().endswith('\n'):
            flag=True

似乎它从未将标志变量设置为真。

如果您可以分享您书中的一些示例,将对每个人都更有帮助。

【讨论】:

  • 我共享了您共享的相同代码,只需在第一个 if 块中将标志设置为 true。
  • 当我将第一个标志设置为 true 时,它​​会在每行添加 2 个空行。
【解决方案4】:

只要没有全部大写的段落,这应该可以工作:

    f = open('file.txt')

    for line in f:
    line = line.strip()
    if line:  
        for c in line:
            if c < 'A' or c > 'Z': # check for non-uppercase chars
                break
        else:        # means the line is made of all caps i.e. I, II, etc, meaning new section
            f.readline()  # discard chapter headers and empty lines
            f.readline()
            f.readline()
            print(f.readline().rstrip()) # print first paragraph

    f.close()

如果您也想获取最后一段,您可以跟踪上次看到的包含小写字符的行,然后在找到全大写行(I、II 等)后立即跟踪,指示新部分,然后打印最近的一行,因为那将是上一节的最后一段。

【讨论】:

  • @TuğcanDemir 我做了一些细微的更改以删除空行并使代码更具可读性。此代码(和以前的版本)与您在上面提供的示例一起使用。你能提供给你这些结果的示例部分吗?
【解决方案5】:

TXR解决方案

$ txr firstpar.txr 数据 有一个广阔的令人着迷的人类兴趣领域,就在我们的门外,到目前为止还很少有人探索。这是动物智能的领域。 我在这里要做的是,找到大写的行,并将它们全部放在一个数组中。然后,使用 index 方法,通过比较我创建的这个数组的这些元素的索引,我将找到每个部分的第一段和最后一段。

firstpar.txr中的代码:

@(重复) @num @标题 @firstpar @ (要求 (and (

基本上,我们在输入中搜索绑定numtitlefirstpar 变量的三元素多行模式的模式匹配。现在这种模式可以在错误的地方匹配,所以添加一些带有require 断言的约束启发式。节号必须是短行,标题行必须包含一些大写字母,不能包含小写字母。此表达式是用 TXR Lisp 编写的。

如果我们得到与此约束条件的匹配项,则输出在firstpar 变量中捕获的字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 2011-08-10
    • 2013-02-08
    • 2014-04-07
    • 2021-11-01
    相关资源
    最近更新 更多