如何根据文本文件中的特定单词过滤特定值并将其存储在列表中? [英] How to Filter specific values against specific words from text file and store it in list?

查看:56
本文介绍了如何根据文本文件中的特定单词过滤特定值并将其存储在列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像我有一个文本文件abc.txt一样,

Like i have a text file abc.txt and it is like this

we 2 rt 3 re 3 tr vh kn mo
we 3 rt 5 re 5 tr yh kn me
we 4 rt 6 re 33 tr ph kn m3
we 5 rt 9 re 34 tr oh kn me
we 6 rt 8 re 32 tr kh kn md

现在我想要针对tr的值,并在过滤后应该得到此结果

now i want the values against the tr and after filtering it should get this result

[vh,yh,ph,oh,kh]

谁能告诉我该怎么做.应该为它写什么代码

can anyone tell how to do it.what code should be write for it

推荐答案

您可以将行拆分为之前 tr之后 tr第二部分中的单词.

You can split the lines as before tr and after tr and obtain the first word in the second part.

[ line.split(' tr ')[1].split()[0] for line in file ] 

如果有多个tr,则该表达式收集第一个后的单词.或者,此命令收集一行中最后一个tr之后的单词:

If there is more than one tr, the expression collects the word after the first one. Alternatively, this one collects the words after the last tr in a line:

[ line.split(' tr ')[-1].split()[0] for line in file ]

这篇关于如何根据文本文件中的特定单词过滤特定值并将其存储在列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆