python-3.x 如何在行中搜索值并检查它是否与给定条件匹配

o4tp2gmn  于 2022-11-26  发布在  Python
关注(0)|答案(2)|浏览(130)

我有一个文件in.txt

name="XYZ_PP_0" number="0x12" bytesize="4" info="0x0000001A"
name="GK_LMP_2_0" number="0xA5" bytesize="8" info="0x00000000bbae321f"
name="MP_LKO_1_0" number="0x356" bytesize="4" info="0x00000234"
name="PNP_VXU_1_2_0" number="0x48A" bytesize="8" info="0x00000000a18c3ba3"
name="AVU_W_2_3_1" number="0x867" bytesize="1" info="0x0b"

从这个文件中,我需要搜索number="0x867",并检查它的信息值是否与预期的给定信息值0x0a匹配。如果匹配,则打印匹配,否则不匹配。
接下来,我需要搜索number="0x12"并存储其信息值,即info="0x0000001A",然后搜索number="0x356"并将其信息值info="0x00000234"存储到另一个变量。该值应等于先前信息值+0x00000004(即0x0000001A + 0x00000004 = 0x0000001E)。

如果结果值与info="0x00000234"匹配,则打印number="0x12" info value 0x00000012 + 0x00000004 matches to info value of number="0x356".
否则print resulted value not matching

这是目前在python中的尝试:

with open("in.txt", "r") as infile:

     XYZ = False
     MP = False
     AVU = False
 
     xyz = ['number="0x12"', 'info="0x0000001A"']
     mp  = ['number="0x356"', 'info="0x00000234"']
     avu = ['number="0x867"', 'info="0x0b"']

     for line in infile:
         if all(x in line for x in xyz):
            XYZ = True
            continue

         if all(x in line for x in mp):
            MP = True
            continue
 
         if all(x in line for x in avu):
            AVU = True
            continue

但这段代码只会检查该行是否存在于file中。它不会检查上面提到的条件。
有没有一种方法可以在文本文件中搜索数字,并将其信息值存储到变量中?

czq61nw1

czq61nw11#

你必须转义双引号,或者你可以使用单引号,这样你的字符串可以有双引号,就像这样:

'number="0x12"'

同样,在if条件中,第一部分是错误的,循环如下:

xyz_list = ['number="0x12"', 'info="0x0000001A"']
mp_list  = ['number="0x356"', 'info="0x00000234"']
avu_list = ['number="0x867"', 'info="0x0b"']

for line in infile:
     if all(x in line for x in xyz_list):
         XYZ = True
         continue

     if all(x in line for x in mp_list):
         MP = True
         continue
 
     if all(x in line for x in avu_list):
         AVU = True
         continue

all()函数将检查行中的子字符串,如果所有子字符串都存在,则返回true。

fivyi3re

fivyi3re2#

尝试将.txt文件转换为 Dataframe ,并使用Pandas Dataframe 应用条件

import pandas as pd
df = pd.read_fwf('myfile.txt')
or 
df = pd.read_csv('myfile.txt', sep=" ")
or 
df = pd.read_csv('myfile.txt', ,delimiter="\t")
or 
df = pd.read_csv('myfile.txt', sep=" ", header=None, names=["Pos", "Lang", "Perc"])

相关问题