簡體   English   中英

查找文本中的數字

[英]Finding the digits in text

我有一個包含以下內容的文件:

&ACCESS RVP1
&REL 3
&PARAM DISKPATH = KRC:\R1\Program\new
DEF SETUP_WELD()
;call LASER_EN();

$out[27]=false;  START=OFF
$out[26]=false;  STROBE=OFF
$out[25]=false;  SELECT 8=OFF
$out[24]=false;  SELECT 7 =OFF
$out[23]=false;  SELECT 6 =OFF
$out[22]=false;  SELECT 5 =OFF
$out[21]=false;  SELECT 4 =OFF
$out[20]=false;  SELECT 3 =OFF
$out[19]=false;  SELECT 2 =OFF
$out[18]=false;  SELECT 1 =OFF
$out[17]=false;  SELECT 0 =OFF
$out[28]=true;  ENABLE=ON

END

我需要在方括號[]中找到該值,並將其寫入數組。 結果,我應該得到下一個結果:

[ '27', '26','25','24','23','22','21','20','19','18','17','28']

我必須使用Python來做。 我對此很陌生,請您給我一個提示,最合適的方法是什么?

我的想法是這樣的:我將文件讀入數組,然后我在考慮使用搜索數組元素:

def reading():
    with open ('Setup_Weld.src') as f:
        array1=[row.strip() for row in f]

但是我不知道如何搜索數組元素。

UPD:找到了答案。 工作代碼為:

def reading():
    with open ('Setup_Weld.src') as f:
        stripped=[row.strip() for row in f]
        setup_weld_num = [re.search(r'\[(.*?)\]',i).group(1) for i in stripped if re.search(r'\[(.*?)\]',i)]
        print(setup_weld_num)
reading()

使用正則表達式

import re
with open(file_name) as file_object:
    data=file_object.read().replace('\n', '')
    re.findall(r"\[(.*?)\]",data)

試試正則表達式,這就是你想要的,

import re
def reading():
    with open ('Setup_Weld.src') as f:
        stripped=[row.strip() for row in f]
        my_num_list = [re.search(br'\[(.*?)\]',i).group(1) for i in stripped if re.search(br'\[(.*?)\]',i)]
        print(my_num_list)
reading()        

python3輸出,

mohideen@botvfx-dev:~/Desktop$ python3 run.py 
[b'27', b'26', b'25', b'24', b'23', b'22', b'21', b'20', b'19', b'18', b'17', b'28']
mohideen@botvfx-dev:~/Desktop$ 

這是我的輸出,

這是我的輸出,

由於格式非常簡單,因此您無需使用正則表達式就可以執行此操作,只需使用Python的字符串方法即可。 這是您開始的改編:

def reading():
    with open ('Setup_Weld.src') as f:
        array1=[row.strip() for row in f]
        return [line[5:].split(']')[0] for line in array1]

這將刪除每行的前四個字符,然后將部分保留在右括號之前。

輸出:

['27', '26', '25', '24', '23', '22', '21', '20', '19', '18', '17', '28']

暫無
暫無

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

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