![](/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.