![](/img/trans.png)
[英]Store a list of specific values from json output into a text file in Python
[英]How to Filter specific values against specific words from text file and store it in list?
就像我有一个文本文件abc.txt一样
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的值,过滤后应该得到这个结果
[vh,yh,ph,oh,kh]
谁能告诉我该怎么做。应该为它编写什么代码
mylist = [line.split()[7] for line in myfile]
如果它始终是第8列,则应该可以工作。
如果tr
的位置可变,则可以
mylist = []
for line in myfile:
items = line.split()
mylist.append(items[items.index("tr")+1])
您可以分割线作为前 tr
和后 tr
,并获得在第二部分的第一个字。
[ line.split(' tr ')[1].split()[0] for line in file ]
如果有多个tr
,则表达式将在第一个之后收集单词。 或者,该行收集一行中最后一个tr
之后的单词:
[ line.split(' tr ')[-1].split()[0] for line in file ]
您的问题不太清楚。 这是你所追求的吗?
[line.split()[7] for line in open("abc.txt")]
它从每一行返回第八个“单词”。
如果我正确理解,则应该执行以下操作(未经测试):
resultArray = []
for aString in yourFile:
anArray = aString.split()
for i in range(0, len(anArray) - 1): //-1 in case tr is at the end of array
if anArray[i] == 'tr':
resultArray.append(anArray[i + 1])
from operator import itemgetter
# tr value is in the 8th column
tr = itemgetter(7)
print map(tr, (line.split() for line in myfile.readlines()))
可以尝试以下方法:
def filter_words(filename, magic_word):
with open(filename) as f:
all_words = f.read().strip().split()
filtered_words = []
i = 0
while True:
try:
i = all_words.index(magic_word, i) + 1
filtered_words.append(all_words[i])
except IndexError, ValueError:
break
return filtered_words
如果'tr'恰好是提供的文本文件中的最后一个单词,则该算法不会失败。
例:
>>> filter_words('abc.txt', 'tr')
['vh', 'yh', 'ph', 'oh', 'kh']
使用正则表达式会更简单吗?
如果'we','rt','re'和'tr'在它们的位置确实是恒定的:
import re
ch = '''
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'''
print re.findall('(?<= tr )([^ ]+)',ch)
如果没有,那么该职位将成为判断该抓什么的标准:
import re
ch = '''
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'''
print [ mat.group(1)
for mat in re.finditer('^(?:\w+ \d+ ){3}\w+ ([^ ]+) .+',ch,re.M)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.