简体   繁体   English

如何根据文本文件中的特定单词过滤特定值并将其存储在列表中?

[英]How to Filter specific values against specific words from text file and store it in list?

Like i have a text file abc.txt and it is like this 就像我有一个文本文件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

now i want the values against the tr and after filtering it should get this result 现在我想要针对tr的值,过滤后应该得到这个结果

[vh,yh,ph,oh,kh]

can anyone tell how to do it.what code should be write for it 谁能告诉我该怎么做。应该为它编写什么代码

mylist = [line.split()[7] for line in myfile] 

should work if it's always the 8th column. 如果它始终是第8列,则应该可以工作。

If the position of tr is variable, you could do 如果tr的位置可变,则可以

mylist = []
for line in myfile:
    items = line.split()
    mylist.append(items[items.index("tr")+1])

You can split the lines as before tr and after tr and obtain the first word in the second part. 您可以分割线作为 tr tr ,并获得在第二部分的第一个字。

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

If there is more than one tr , the expression collects the word after the first one. 如果有多个tr ,则表达式将在第一个之后收集单词。 Alternatively, this one collects the words after the last tr in a line: 或者,该行收集一行中最后一个tr之后的单词:

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

Your question is not quite clear. 您的问题不太清楚。 Does this what you are after? 这是你所追求的吗?

[line.split()[7] for line in open("abc.txt")]

It returns the eighth "word" from every line. 它从每一行返回第八个“单词”。

If I understand correctly, something like this should do the job (not tested): 如果我正确理解,则应该执行以下操作(未经测试):

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()))

One may try the following: 可以尝试以下方法:

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

This algorithm does not fail in case 'tr' happens to be the last word in the provided text file. 如果'tr'恰好是提供的文本文件中的最后一个单词,则该算法不会失败。

Example: 例:

>>> filter_words('abc.txt', 'tr')
['vh', 'yh', 'ph', 'oh', 'kh']

Wouldn't be simpler to use a regex ? 使用正则表达式会更简单吗?

If 'we' , 'rt' , 're' , 'tr' are really constant at their places : 如果'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)

If not, and then the position being the criterium to determine what to catch: 如果没有,那么该职位将成为判断该抓什么的标准:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM