首页 > 解决方案 > 根据另一个列表Python中的字符串仅输出txt文件中的特定项目

问题描述

我有一个字符串列表:

myStrings = [Account,Type, myID]

我也有一个txt filenumbers这些字符串相关的,例如:

[90: 'Account', 5: 'Type', 6: 'MyID', 8: 'TransactionNum', 9: 'Time']

我怎样才能打印only the numbers and strings in the txt file出来in myStrings。例如,由于'Time' is not in myStrings,我do not want to print it。我也想做这个txt file a list

标签: pythonlisttext-files

解决方案


在你说文件没有[&]之后,可以让它像这样工作:

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']

推荐阅读