python-3.x - 如何从 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
解决方案
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
这只是打印值,但应该相当容易地存储您想要的值。
推荐阅读
- spring - 执行器刷新未提交的本地文件更改
- javascript - 将 CSV 转换为带有标头的 JSON
- c# - 如何引用多列列表<>中的列并在 FindControl 中使用列值
- r - 有没有办法强制 ode() [deSolve-R 包] 在 ode 函数的每个集成步骤中提供输出
- c - 使用 beaglebone Black SPI 在 DIP203-6 LCD 屏幕上显示字符
- wordpress - 将 NPM 模块导入 Wordpress ReactJS 插件
- python - 如果满足某些条件,将行转换为 pandas 数据框的列
- python - 如何在 Matplotlib 中与线程一起执行动画?
- matrix - 当它是矩阵时,EMGU imshow不显示图像
- r - 特征选择的方差分析