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

  • Post author:
  • Post category: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…