簡體   English   中英

如何在線搜索值並檢查它是否符合給定條件

[英]How to search for a value in line and check if it matches given condition

我有一個文件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 匹配。 如果它匹配 print matches else 不匹配。

然后接下來我需要搜索number="0x12"並將其信息值存儲,即info="0x0000001A" ,然后搜索number="0x356"並將其信息值info="0x00000234" "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  



       

但是這段代碼只會檢查該行是否存在於文件中。 它不會檢查上述條件。

有沒有一種方法可以在文本文件中搜索數字並將其信息值存儲到變量中?

你必須轉義雙引號,或者你可以使用單引號,這樣你的字符串就可以像這樣在其中包含雙引號:

'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() function 將檢查行中的子字符串,如果全部存在則返回 true。

嘗試將 .txt 文件轉換為 dataframe 並使用 pandas datframe 應用條件

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"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM