簡體   English   中英

如何在python中的txt文件中提取數字

[英]how to extract the numbers in txt file in python

我有一個這樣的txt文件:

ASP62-Main-N     LYS59-Main-O    100.00%
THR64-Side-OG1   VAL60-Main-O    100.00%
ALA66-Main-N     LEU61-Main-O    100.00%
LYS33-Main-N     SER30-Main-O    100.00%

我想獲取“ -Main”或“ -Side”之前的數字,結果如下:

62 59
64 60
66 61
33 30

我寫了一些代碼,但是結果只顯示了“ -Main”。

f1 = open(filename1)
for line in f1.readlines():
    N=re.compile(r'(\d+)-Main|-Side')
    n=N.findall(line)
    print (n)

結果如下所示:

['62', '59']
['', '60']
['66', '61']
['33', '30']

請有人給我一些建議。

或作為完整代碼:

import re
with open('filename.txt','r') as f:
   for i in f:
      print(' '.join(re.findall('\d{2}',i)[:-2]))

輸出:

62 59
64 60
66 61
33 30

正如@JosephSible所提到的,由於交替的優先級較低,因此您應該在交替中對模式進行分組,但是在這種情況下,應該對-Main-Side使用非捕獲組,因為您實際上並不希望在輸出中使用它們:

N=re.compile(r'(\d+)(?:-Main|-Side)')

另外,您可以使用前瞻模式,因此不需要任何捕獲組:

N=re.compile(r'\d+(?=-Main|-Side)')

這是一個優先問題。 交替發生得足夠晚,以至於您的正則表達式被解析為“數字后跟-Main”或“ -Side”。 使用此正則表達式代替: (\\d+)(-Main|-Side)

暫無
暫無

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

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