我有一个太大的txt文件,有几条相似的行,如下所示:
word1 word2 word3 word4 -553.75
我对位置[4]“价值”感兴趣,最后一行是-553.75
我的档案文字:
.
.
word1 word2 word3 word4 -553.20
.
.
.
word1 word2 word3 word4 -553.25
.
.
.
word1 word2 word3 word4 -553.75
.
.
.
我的剧本:
def main():
oTE_list = []
oTE = []
with open("file.txt","r") as f:
text = f.readlines()
for line in text:
if line[0] == 'word1' and line[1] == 'word2' and line[2] == 'word3' and line[3] == 'word4':
oTE_list.append(line[4])
# Change Lists To Number Format
for idx, item in enumerate(oTE_list):
if idx == len(oTE_list) - 1:
print(item)
if __name__ == '__main__':
main()
但我不知道为什么它不适用于我!
提前谢谢。
答案 0 :(得分:1)
该行是字符串而不是单词列表,要将其转换为单词使用列表strip
和\n
,然后才能删除def main():
oTE_list = []
oTE = []
with open("file.txt","r") as f:
text = f.readlines()
for line in text:
line = line.strip().split()
if line[0] == 'FINAL' and line[1] == 'SINGLE' and line[2] == 'POINT' and line[3] == 'ENERGY':
oTE_list.append(line[4])
# Change Lists To Number Format
for idx, item in enumerate(oTE_list):
if idx == len(oTE_list) - 1:
print(item)
if __name__ == '__main__':
main()
InputStream inputStream = assetManager.open("cert.cer");
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
X509Certificate certificate = (X509Certificate) cf.generateCertificate(inputStream);
答案 1 :(得分:1)
方式不使用re并从文件末尾读取
import re
with open("file1.txt","r") as f:
for line in reversed(f.readlines()):
if re.search('word1.*word2.*word3.*word4',line):
print(line.split(' ')[-1])
break