[英]How do I print only the first instance of a string in a text file using Python?
I am trying to extract data from a .txt file in Python.我正在尝试从 Python 中的 .txt 文件中提取数据。 My goal is to capture the last occurrence of a certain word and show the next line, so I do a reverse () of the text and read from behind.
我的目标是捕获某个单词的最后一次出现并显示下一行,因此我对文本进行了反向 () 并从后面阅读。 In this case, I search for the word 'MEC', and show the next line, but I capture all occurrences of the word, not the first.
在这种情况下,我搜索“MEC”这个词,并显示下一行,但我捕获了该词的所有出现,而不是第一个。
Any idea what I need to do?知道我需要做什么吗?
Thanks!谢谢!
This is what my code looks like:这是我的代码的样子:
import re
from file_read_backwards import FileReadBackwards
with FileReadBackwards("camdex.txt", encoding="utf-8") as file:
for l in file:
lines = l
while line:
if re.match('MEC', line):
x = (file.readline())
x2 = (x.strip('\n'))
print(x2)
break
line = file.readline()
The txt file contains this: txt 文件包含以下内容:
MEC
29/35
MEC
28,29/35
And with my code print this output:用我的代码打印这个输出:
28,29/35
29/35
And my objetive is print only this:我的目标是只打印这个:
28,29/35
Get rid of the extra imports and overhead.摆脱额外的导入和开销。 Read your file normally, remembering the last line that qualifies.
正常阅读您的文件,记住符合条件的最后一行。
with ("camdex.txt", encoding="utf-8") as file:
for line in file:
if line.startswith("MEC"):
last = line
print(last[4:-1]) # "4" gets rid of "MEC "; "-1" stops just before the line feed.
If the file is very large, then reading backwards makes sense -- seeking to the end and backing up will be faster than reading to the end.如果文件非常大,那么向后读取是有意义的——寻找到最后并备份将比读取到最后更快。
This will give you the result as well.这也会给你结果。 Loop through lines, add the matching lines to an array.
循环遍历行,将匹配的行添加到数组中。 Then print the last element.
然后打印最后一个元素。
import re
with open("data\camdex.txt", encoding="utf-8") as file:
result = []
for line in file:
if re.match('MEC', line):
x = file.readline()
result.append(x.strip('\n'))
print(result[-1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.