简体   繁体   English

从文件摘录中删除最后一行

[英]Remove last line from file excerpt

I'm trying to copy an excerpt from a txt file into a variable and then printing it. 我试图将摘录从txt文件复制到变量中,然后打印出来。 It looks for tomorrow's date, and then it prints everything between that and the current date. 它会寻找明天的日期,然后打印该日期和当前日期之间的所有内容。 However, today's day is being printed, as it is located before today's date. 但是,由于今天是今天,所以今天才被打印。

Eg: 例如:

Friday 24/5 星期五24/5

[content im looking for] [内容即时搜寻]

Thursday 23/5 星期四23/5

When I try to print this, it includes Thursday as well, which is not a part of what I want to print. 当我尝试打印时,它也包括星期四,这不是我要打印的一部分。

Do you guys have an easy way to remove the Thursday? 你们有简单的方法删除星期四吗?

file=open("plan.txt","r")
s = file.read()
dayresult = ((s.split(str(tomorrowerino)))[1].split(str(todayerino))[0]).strip()
dayresult[dayresult.find('\n')+1:dayresult.rfind('\n')]
print dayresult

Here is what it outputs: 它输出的是:

"

Geografi Geografi

Vi har geografi istedenfor samfunnsfag. Vit har geografi istedenfor samfunnsfag。 Norsk 诺尔斯克

Les side 75 til 82, og gjør oppsummeringsoppgavene 1 til 10 side 83. 侧面75到82,以及侧面1到10侧面83。

Torsdag 托斯达格

"

The second to last line is what I tried to use to remove the Torsdag, but it didn't do anything. 倒数第二行是我试图删除Torsdag的内容,但没有执行任何操作。

(Torsdag means Thursday, and that is what I want removed) (Torsdag表示星期四,这就是我要删除的内容)

Also, the days will vary, so I can't just subtract that from the string. 另外,日子会有所不同,所以我不能只从字符串中减去那一天。

(I have the code for the variables if you need them to help, but I don't see how they're relevant atm.) (如果您需要变量的帮助,我会提供代码,但我看不到它们与atm的关系。)

Thank you :) 谢谢 :)

I'll leave it as an answer as well, for any who will encounter similar situations: 对于也会遇到类似情况的任何人,我也将其作为答案:

Whenever you use list slicing, it doesn't change the list (or any other sequence type variables like str , tuple , unicode ) it is called on, but creates a new one. 每当您使用列表切片时,它都不会更改被调用的列表(或任何其他序列类型变量,如strtupleunicode ),但是会创建一个新列表。 You need to reassign the value of the sliced list to itself: 您需要将切片列表的值重新分配给它自己:

dayresult = dayresult[:dayresult.rfind('\n')]

Also, the slicing happens from the first character, until the last row. 同样,切片从第一个字符开始,直到最后一行。

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

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