簡體   English   中英

從python中的文本文件中分離值

[英]Separating values from text file in python

我正在嘗試讀取包含以下數據的文本文件:

 362  147
 422   32
 145   45
 312   57
  35  421
 361  275

我想將這些值分成對,所以 362 和 147 將是對 1、422 和 32 對 2 等等。

但是我在 5 對中遇到了一個問題,應該是 35,421 但由於某種原因我的代碼沒有正確分割這對,我認為這是因為空格,因為只有這對有一個兩位數,然后是一個 3 位數字. 但我不知道如何解決這個問題,這是我的代碼:

def __init__(filename):
    f = open(filename, "r") #reads file
    #print (f.read) # test if file was actually read 
    f1 = f.readlines() # reads individual lines
    counter = 0
    for line in f1: 
        values = line.split("  ") #splits the two values for each line into an array
        value1 = values[0].strip() #.strip removes spaces at each values
        value2 = values[1].strip()
        counter = counter + 1
        print('\npair: {}'.format(counter))
        #print(values)
        print(value1)
        print(value2)

我得到的輸出:

pair: 1
362
147

pair: 2
422
32

pair: 3
145
45

pair: 4
312
57

pair: 5

35

pair: 6
361
275

嘗試這個 :

def __init__(filename):
    with open(filename, "r") as f:
        lines = [i.strip() for i in f.readlines()]
        for line_num, line in enumerate(lines):
            p1, p2 = [i for i in line.split() if i]
            print(f"pair: {line_num+1}\n{p1}\n{p2}\n\n")

注意:始終嘗試with open()一起使用。 通過這種方式,python 會在最后自動關閉文件。

您的代碼的問題在於您沒有檢查拆分values后提取的單詞是否為空字符串。 如果您為每行打印values ,對於第 5 對,您會注意到它是['', '35', '421\\n'] 這個的第一個值是一個空字符串。 您可以將代碼更改為:

def __init__(filename):
    f = open(filename, "r") #reads file
    #print (f.read) # test if file was actually read 
    f1 = f.readlines() # reads individual lines
    counter = 0
    for line in f1: 
        values = line.split() #splits the two values for each line into an array; Addendum .split(" ") is equivalent to .split()
        values = [i for i in values if i] #Removes the empty strings
        value1 = values[0].strip() #.strip removes spaces at each values
        value2 = values[1].strip()
        counter = counter + 1
        print('\npair: {}'.format(counter))
        #print(values)
        print(value1)
        print(value2)

改變這一行:

values = line.split("  ")

到:

values = line.split()

暫無
暫無

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

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