简体   繁体   English

如何在 Python 中打印文本文件每个段落的第一行?

[英]How do I print the first line of each paragraph of a text file in Python?

Let's say I have a text file like this:假设我有一个这样的文本文件:

Tom
15
Basketball

James
16
Tennis
Track
Choir

Tim
14
Band
Class Chairman

I would like to display this:我想显示这个:

Tom
James
Tim

My program allows the user to append more information into the txt file.我的程序允许用户将更多信息附加到 txt 文件中。 While I could make it such that it only reads line 1, 5 and 11, the problems lies with displaying any added information.虽然我可以让它只读取第 1、5 和 11 行,但问题在于显示任何添加的信息。 Each paragraph might also have different amount of lines.每个段落也可能有不同数量的行。 From what I know (and find online), there isn't a way to print only the first line of each paragraph of a txt file without importing external tools.据我所知(并在网上找到),没有办法在不导入外部工具的情况下只打印 txt 文件每个段落的第一行。 Is there a convoluted way to do this or is there a different approach to solve this?是否有一种复杂的方法可以做到这一点,或者是否有不同的方法来解决这个问题?

f = open('filename.txt', 'rt')

for entry in f.read().split('\n\n'):
    print(entry[0 : entry.index('\n')])

filename.txt is the name of that text file, rt is the file opening mode: r stands for 'read' (read-only mode) and t for 'text' file. filename.txt是该文本文件的名称, rt是文件打开模式: r代表“读取”(只读模式), t代表“文本”文件。

Every entry (paragraph) is separated by two newlines (think about it) so we .split() by that and for every such entry, we know that the first line is the name, so we splice the string as [0 : entry.index('\\n')] as entry.index('\\n') gives the index just next to the first newline in the entry.每个条目(段落)由两个换行符(想想看)分隔,所以我们.split()通过它和每个这样的条目,我们知道第一行是名称,所以我们将字符串拼接为[0 : entry.index('\\n')] as entry.index('\\n')给出条目中第一个换行符旁边的索引。

Also, make sure the file does exist there before running it, otherwise it'll throw an error.另外,请确保该文件在运行之前确实存在,否则会引发错误。

Use a variable to keep track of whether the line on the previous iteration contained any text or not.使用变量来跟踪上一次迭代中的行是否包含任何文本。 You want the lines which have text, and where the previous line (if any) did not have any text.您需要包含文本的行,以及前一行(如果有)没有任何文本的行。

previous_has_text = False
with open('input.txt') as f:
    for line in f:
        line = line.strip()
        if line:
            # THIS line has text
            if not previous_has_text:
                print(line)
            previous_has_text = True  # ready for next iteration
        else:
            previous_has_text = False  # likewise

Gives:给出:

Tom
James
Tim

With this method, it does not matter if there is more than one blank line between paragraphs.使用这种方法,段落之间是否有多个空行都没有关系。 Also if the "blank" line contains a space it will still work.此外,如果“空白”行包含空格,它仍然可以工作。

暂无
暂无

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

相关问题 如何使用每个新段落的第一行中的键从按段落分隔的文本文件在python中制作字典? - How to make a dictionary in python from a text file seperated by paragraph with the key in the first line of each new paragraph? Python:如何检查文本文件,将其与另一个文本文件中的每一行进行比较,并打印不匹配的行 - Python: How to check a text file, compare it to each line in another text file, and print the lines that do not match Python:打印/获取每个段落的第一句话 - Python: print/get first sentence of each paragraph 如何在Python的已保存文件中的包含某些文本的行之后打印行? - How do I print a line following a line containing certain text in a saved file in Python? 我如何在 python 的 while 循环中逐行打印 a.txt 文件中的每一行 - How do i print each line in a .txt file one by one in a while loop in python 如何将文件中的每一行拆分为三个变量然后打印出来? - How do I split each line in the file into three variables and then print it? 如何使用 Python 仅打印文本文件中字符串的第一个实例? - How do I print only the first instance of a string in a text file using Python? 在python中打印第一段 - print first paragraph in python 如何通过不触摸 python 中文本文件的每一行中该单词的 rest 来替换每行中的第一个特定特殊字符 - How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python 如何在python中按行打印变量“new_text” - How do I print the variable "new_text" in line in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM