[英]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.