[英]Output only specific items in a txt file according to strings from another list Python
我有一個字符串列表:
myStrings = [Account,Type, myID]
我還有一個txt file
其中包含與這些字符串關聯的numbers
,例如:
[90: 'Account', 5: 'Type', 6: 'MyID', 8: 'TransactionNum', 9: 'Time']
如何only the numbers and strings in the txt file
打印only the numbers and strings in the txt file
in myStrings
only the numbers and strings in the txt file
。 例如,由於'Time' is not in myStrings
,我do not want to print it
。 我也想讓這個txt file a list
在你說文件沒有[
& ]
,可以讓它像這樣工作:
import json
myStrings = ['Account','Type', 'myID']
with open('text-file.txt') as filename:
file_text = filename.read()
file_text_list = file_text.split(',')
file_text_dict = {}
for item in file_text_list:
k, v = item.split()
v = v.replace("'", "")
k = k.replace(":", "")
if v in myStrings:
file_text_dict[k] = v
print(file_text_dict) # output => {'90': 'Account', '5': 'Type'}
print(list(file_text_dict.values())) # output => ['Account', 'Type']
這應該可以幫助你:
myStrings = ['Account','Type', 'myID']
f = open("D:\\Test.txt","r")
txt = f.read()
f.close()
txt = txt.replace('\n',' ')
txt = txt.split(',')
txtlst = []
for x in txt:
txtlst.append(x.split(':'))
numslst = [int(txtlst[i][0]) for i in range(len(txtlst))]
strlst = []
for i in txtlst:
for j in i:
try:
int(j)
except ValueError:
strlst.append(j.replace("'",""))
for x in range(len(strlst)):
strlst[x] = strlst[x].replace(' ','')
for x in range(len(strlst)):
if strlst[x] in myStrings:
print(numslst[x])
print(strlst[x])
輸出:
90
Account
5
Type
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.