python - 根据另一个列表Python中的字符串仅输出txt文件中的特定项目
问题描述
我有一个字符串列表:
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
出来in myStrings
。例如,由于'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']
推荐阅读
- kubernetes - gitlab-ci 和 kubectl 问题
- mysql - MySQL NULL AND 1 返回 NULL
- html - 我们必须为逗号输入 HTML 代码吗?
- html - 用于 nil:NilClass 的未定义方法
- c++ - 全局范围内变量和函数的递归依赖
- powerbi - 计算列下一个日期 Power BI
- elixir - 如何在 Phoenix 上一次将字符串参数转换为整数
- c# - 检查一个字符数组的元素是否出现在另一个字符数组中
- python - 使用 smtplib 库在 python 中登录错误
- javascript - CSS如何在调整页面大小时防止元素重叠并保持元素固定?