簡體   English   中英

從文件中讀取一組元組編號

[英]Read set of tuple numbers from a file

我有一個帶有前兩行的文件,如下所示:

(1,233)(44,444)(2323,545)(0,0)(22,2)(5,0)(222,2)(0,5)(12,2)(22,3)
(0,223)(44,424)(123,545)(0,1)(42,2)(5,0)(52,2)(0,6)(17,4)(3,3)

我想閱讀每個元組並獲取每個數字(不帶逗號和括號)。 我這樣讀:

file = filedialog.askopenfilename(filetypes=[("Text files","*.txt")])
if file is None:
    return False

with open(file, 'r') as f:
    lines = f.read().split("\n")
    firstLine = lines[0]
    secondLine = lines[1]

    # Run loop here to get the tuple values
    # firstNum = tuple[0]
    # secondNum = tuple[1]

    # Go to next line and do the same

我該怎么做? 任何幫助,將不勝感激。

我會去尋找正則表達式:

[(int(x), int(y)) for x,y in re.findall(r"\((\d+),\s*(\d+)\)", line)]
# [(1, 233), (44, 444), (2323, 545), (0, 0), (22, 2), (5, 0), (222, 2), ...]

另一個有趣的解決方案是通過在兩對之間插入逗號將行轉換為有效的Python元組,然后應用ast.litereal_eval

list(ast.literal_eval(line.replace(")", "),")))
# [(1, 233), (44, 444), (2323, 545), (0, 0), (22, 2), (5, 0), (222, 2), ...]

這是使用ast.literal_eval()的一種相對簡單的方法:

import ast

with open('tuple.txt') as file:
    for line in file:
        numbers = ast.literal_eval(line.replace(')(', '),('))
        print('numbers: {}'.format(numbers))
        for _1st_num, _2nd_num in numbers:
            print(_1st_num, _2nd_num)

輸出:

numbers: ((1, 233), (44, 444), (2323, 545), (0, 0), (22, 2), (5, 0), (222, 2), (0, 5), (12, 2), (22, 3))
1 233
44 444
2323 545
0 0
22 2
5 0
222 2
0 5
12 2
22 3
numbers: ((0, 223), (44, 424), (123, 545), (0, 1), (42, 2), (5, 0), (52, 2), (0, 6), (17, 4), (3, 3))
0 223
44 424
123 545
0 1
42 2
5 0
52 2
0 6
17 4
3 3

第一種方式

用空格替換所有方括號和逗號,然后拆分該行以刪除空格。 因此,您將獲得所有數字的固定列表。 通過遍歷列表並獲得索引ii+1 ,可以成對獲得它們。

>>> line = "(1,233)(44,444)(2323,545)(0,0)(22,2)(5,0)(222,2)(0,5)(12,2)(22,3)"
>>> line_edited = line.replace("(", " ").replace(")", " ").replace(",", " ").split()
>>> line_edited
['1', '233', '44', '444', '2323', '545', '0', '0', '22', '2', '5', '0', '222', '2', '0', '5', '12', '2', '22', '3']
>>> for i in xrange(0, len(line_edited), 2):
    print line_edited[i], line_edited[i+1]


1 233
44 444
2323 545
0 0
22 2
5 0
222 2
0 5
12 2
22 3

第二種方式

與第一種方法類似,不同之處在於只用空格替換並分割了括號。 現在,您將獲得一個字符串列表"first_number,second_number" ,因此您可以遍歷這些字符串並在逗號處拆分以獲取該對。

>>> line_edited = line.replace("(", " ").replace(")", " ").split()
>>> line_edited
['1,233', '44,444', '2323,545', '0,0', '22,2', '5,0', '222,2', '0,5', '12,2', '22,3']
>>> for pair in line_edited:
    first_number, second_number = pair.split(",")
    print first_number, second_number


1 233
44 444
2323 545
0 0
22 2
5 0
222 2
0 5
12 2
22 3

您可以在此處閱讀有關替換字符串中多個字符的更多信息。

您也可以像以下示例一樣進行操作(我假設您的輸入文件稱為input_file ):

data = (k.rstrip().replace("(", "").replace(")", " ").strip().split(" ") for k in open("input_file", 'r'))

for k in data:
    for j in (i.split(',') for i in k):
        print("{} {}".format(j[0], j[1]))

輸出:

1 233
44 444
2323 545
0 0
22 2
5 0
222 2
0 5
12 2
22 3
0 223
44 424
123 545
0 1
42 2
5 0
52 2
0 6
17 4
3 3

如果您可以保持堵嘴反射足夠長的時間,就可以這樣做:

with open(file, 'r') as f:
    lines = f.read().split("\n")
    for line in lines:
      input=[scanf("%d,%d)",a) for a in line[1:].split('(')]
      # process each tuple in 'input' before continuing with next line

也許只是用DYZ的答案。

暫無
暫無

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

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