从Python中的文本文件中获得特殊数字的句子

时间:2018-10-09 06:51:26

标签: python python-3.x

我在Visual Studio上研究Python项目。 我像这样将十六进制数更改为二进制数:

print("Enter a hex for converting binary");
hexdec = input("Enter any number in Hexadecimal form: ");
bin_value = bin(int(hexdec,16))[2:]
bin_value = (8 - (len(bin_value)% 8)) * '0' + bin_value
bytes = [bin_value[i:i+8] for i in range(0, len(bin_value), 8)]
' '.join(bytes)
print(' '.join(bytes));

因此,输出如下所示:

00000001

我想从头开始使用二进制数,并逐行读取文件,然后从该文本文件中获取句子的结果:

00000110 Address complete
00001001 Answer
01000001 Application transport
00000001 Blocking 39 

因此,预期输出仅如下所示:

Blocking 39

反正有这样做吗?

2 个答案:

答案 0 :(得分:1)

尝试一下:

key = "00000001"

with open("data.txt") as f:
    for line in f.readlines():
        if line.startswith(key):
            print(line.lstrip(key + " "))

答案 1 :(得分:0)

假定二进制数存储在变量key中,并且您的查找文件作为文件对象f打开:

open('messagetype.txt', 'r') as f:
    for l in f:
        k, v = l.split(maxsplit=1)
        if k == key:
            print(v)

给出示例输入,将输出:

Blocking 39