簡體   English   中英

如何提取方括號之間的數字?

[英]how to extract numbers between square brackets?

我有一個包含文本的文本文件

index of cluster is 18585 points index are [18585, 14290, 18503, 7220, 6835, 10009,6615, 1269, 14161, 26545, 18140, 9292, 20355, 16401, 7713, 582, 1865, 17247, 26256, 19034, 7282, 1847, 19293, 16944, 27748, 29312,.... ] 
index of the cluster is 3014 points index are [ ....] and so on .. 

我需要在單個文件中的每個集群中提取"[""]"之間的數字。 我試圖檢查線路是否有"["然后獲取數字但沒有正常工作

import os 
f = open("cluster.txt","r")
for line in f.readlines():
    if "[" in line:
        print("true")

對於文件中的每一行,您可以使用正則表達式來識別括號內的數據。 然后您可以拆分結果字符串並使用列表理解(或此處所示的 map)為您提供所有數字的列表。

例如:

import re
line = '''index of cluster is 18585 points index are [18585, 14290, 18503, 7220, 6835, 10009,6615, 1269, 14161, 26545, 18140, 9292, 20355, 16401, 7713, 582, 1865, 17247, 26256, 19034, 7282, 1847, 19293, 16944, 27748, 29312]'''
a = re.findall('\[(.*?)\]', line)
if a:
    nums = list(map(int, a[0].split(',')))
    print(nums)

Output:

[18585, 14290, 18503, 7220, 6835, 10009, 6615, 1269, 14161, 26545, 18140, 9292, 20355, 16401, 7713, 582, 1865, 17247, 26256, 19034, 7282, 1847, 19293, 16944, 27748, 29312]

你可以這樣做:

f = open("cluster.txt","r")
for line in f.readlines():
    numbers_only = line.split('[')[1].split(']')[0]
    list_of_number_strings = numbers_only.split(',')
    list_of_numbers = [int(number) for number in list_of_number_strings]

有了這個,您最終將在list_of_numbers列表中將數字轉換為整數。 首先,這會拆分行以僅獲取[]之間的部分,然后拆分其余部分並將它們轉換為整數。 這假定每一行都包含一個列表。 如果某些行具有不同的格式,則您需要為這種情況添加一些額外的邏輯。

您也可以執行以下操作:

f = open("cluster.txt","r")
lst=[]

for line in f.readlines():
    lst += list(map(int, line.split("[").[1].split("]")[0].split(",")))

print(lst)

該列表將獲取文件的所有行。 map 只是將恢復的值轉換為整數。 您只需將 map 轉換為列表,將 append 轉換為主列表。

暫無
暫無

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

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