首页 > 解决方案 > 如何从 txt 文件中提取具有两个条件的行,一个单词和一个数字?

问题描述

我想仅使用 Python 获取有效行中的数字,因此
第 1行中的 1234、345.2、3455
第 3 行中的
7644、6564.1、1325 第 5行中的 89473、8479、2434

txt file

books|1234|345.2|3455|valid
books|9875|5466.1|invalid
books|7644|6564.1|1325|valid
books|5435|4535.2|invalid
books|89473|8479|2434|valid

标签: python-3.x

解决方案


with open("test.txt",'r') as fil: #open file
    for line in fil.readlines(): #read it line by line
        #remove newline and split into list, elements separated by |
        temp=line.strip().split('|') 
        if temp[-1]=="valid": #Check if "valid" is last element
            print(temp[1:-1]) #print all elements between first and last

这只是打印值,但应该相当容易地存储您想要的值。


推荐阅读