python判断文本内容_如何使用python检查文本文件中是否存在数据?

1586010002-jmsa.png

Is anyone can help me to figure out this problem? I got the result 1 and 0 but I can not figure out how to write it to a file.

outfile = "Result.txt"

Array = ["6J", "xx", "ss", "11"]

with open("test.txt", "r") as f:

with open(outfile, "w") as result:

output_list = []

for rec in f.read().splitlines():

rec = rec[:-3]

FBlist = [rec[i:i+2] for i in range(0, len(rec), 2)]

output_list.append(FBlist)

print(output_list)

FBlist_set = set(FBlist)

Array_set = set (Array)

if Array_set & FBlist_set:

print ("found")

result.write("1")

else:

print ("0")

result.write("0")

My test.txt file is 6J7K8L.XY First, I convert that text file be like this ["6J", "7K", "8L"] . The 3 last characters is not include. Why I convert to 2 characters, because I want to compare it each 2 characters and my fixed data also 2 characters. My problem is I can not figure out how to check my fixed data with text file and return 1 or 0.

解决方案

With the limited info you posted it would seem as though you're getting 0 always because you're comparing Array, an array with 4 string elements, with the first 2 elements of each FBlist element you appended to the output_list array. I could only imagine the comparison looking something like this:

["6J", "xx", "ss", "11"] == [element1, element2]

which will always be False. Hoaw about a sample of what's in the test.txt file?

Also: int(True) and int(False) will always give you 1 or 0 respectively so no need for str((0,1)[found]) you can just do str(found)

Edit 1:

In response to your comment, make this adjustment in your code to see what it is you are comparing:

for line in output_list:

print('comparing {arr} == {line} ?'.format(arr=Array, line=line[:3])

found = int(Array == line[:3])

result.write(found)

From your comment I see an immediate problem, Array has 4 item while item[:3] has 3 item so they will never be the same...

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值