如何解决根据来自另一个列表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
的{{1}}。例如,自in myStrings
起,我'Time' is not in myStrings
。我也想做这个do not want to print it
解决方法
在您说文件没有[
和]
之后,可以使它像这样工作:
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','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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。