亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在拆分它們之前如何避免包含字符串和數字的行?

在拆分它們之前如何避免包含字符串和數字的行?

MMTTMM 2021-11-02 20:17:58
我使用python 3,并且我讀取了以幾行包含文本和數字的行開始的文件,并且從某一行開始它只是數字列,最初它們在拆分后也被讀取為str,后來我將它們轉換為浮點數.數據看起來像這樣。我還添加了數字樣本的鏈接https://gist.github.com/Farzadtb/b0457223a26704093524e55d9b46b1a8所以問題是,對于閱讀,我有兩個條件(實際上我希望增加這些條件)使用 try: except 。但這僅適用于劃分拆分方法。但在我開始拆分之前,我需要刪除包含文本的第一行。我知道我應該使用除了值錯誤但這真的行不通!f = io.open(file, mode="r", encoding="utf-8")    #f=open(file,"r")    lines=f.readlines()    x=[]    y=[]    z=[]        for i in lines:        try:            a=[i.strip('\n')]            a1=[float(n) for n in a[0].split(',')]            atot.append(a1)            x.append(a1[3])            y.append(a1[2])            z.append(a1[1])        except :             a=[i.split('\n')]             a1=[float(n) for n in a[0].split()]             x.append(a1[3])             y.append(a1[2])             z.append(a1[1])問題是,由于第一行也可以以數字開頭,因此第一個參數可能會被拆分并添加到“x”和“y”中,但是我得到了 z 的錯誤x=[float(i) for i in x]y=[float(i) for i in y]z=[float(i) for i in z]我想到的一個想法是檢查該行是否可以無錯誤地轉換為浮動,然后繼續拆分,但我不知道該怎么做
查看完整描述

1 回答

?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

你應該試試這個。此代碼使用正則表達式作為一種干凈的方式來查找數據。


import pprint

import re


if __name__ == '__main__':

    # pattern to ignore line containing alpha or :

    ignore_pattern = re.compile(r'[^a-zA-Z:]*[a-zA-Z:]')

    # number pattern

    number_pattern = re.compile(r'[-.\d]+')


    matrix = []


    # open the file as readonly

    with open('data.txt', 'r') as file_:


        # iterator over lines

        for line in file_:

            # remove \n and spaces at start and end

            line = line.strip()

            if not ignore_pattern.match(line):


                found = number_pattern.findall(line)

                if found:

                    floats = [float(x) for x in found]

                    matrix.append(floats)


    # print matrix in pretty format

    pp = pprint.PrettyPrinter()

    pp.pprint(matrix)


    # access value by [row][column] starting at 0

    print(matrix[0][2])

對您的樣本數據進行了測試。這是 python 腳本的標準輸出:


[[-3.1923, 0.6784, -4.6481, -0.0048, 0.3399, -0.2829, 0.0, 24.0477],

 [-3.1827, 0.7048, -4.6257, 0.0017, 0.3435, -0.2855, 0.0, 24.0477],

 [-3.1713, 0.7237, -4.5907, 0.0094, 0.3395, -0.2834, 0.0, 24.0477]]

-4.6481


查看完整回答
反對 回復 2021-11-02
  • 1 回答
  • 0 關注
  • 222 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號