簡體   English   中英

如何讀取文件並將數據轉換為數字?

[英]How can I read a file and convert the data to numbers?

我正在嘗試讀取一個包含

1,2 20000

並可能讀取具有相同類型的其他文本文件,只有更多的數字,例如:

1,2,3 30000 或 2,3,4,5 2000000。

with open('coordinate.txt','r') as file:
    for line in file:
        line = line.strip()
        pieces = line.split()
        data.append(pieces)

然后分配coord = data[0]trial = data[1]但 coord 變為["1,2"]我只是不知道如何通過去掉逗號並制作 numpy 形式來分隔 1 和 2。 如何正確讀取文件並將其分配為我想要的格式?

您可以使用正則表達式拆分多個分隔符。 就像是:

import re
txt = "1,2 20000"
txt_arr = re.split(r'[,\s]\s*', txt)

更多信息在這里

更簡單的方法是使用split方法:

pieces = []
lines = None
with open('cooridnate.txt', 'r') as fp:
    lines = fp.readlines() # Get lines

for line in lines:
    splitted_line = line.rstrip().split(',') # Split line with "," as a delimiter
    pieces.append({
        'coord': int(splited_line[0]),
        'trial': splitted_line[1:]
    }) # Append the splitted in pieces

print(pieces)

您可能還需要創建一個循環進行試用(如果您也想轉換它)。 是你要找的嗎?

暫無
暫無

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

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