根据另一个列表中的字符串仅输出 txt 文件中的特定项目 Python
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
是 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']
这应该对你有帮助:
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
我有一个字符串列表:
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']
这应该对你有帮助:
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