Reading file string into an array (In a pythonic way)

后端 未结 5 833
礼貌的吻别
礼貌的吻别 2020-12-06 03:39

I\'m reading lines from a file to then work with them. Each line is composed solely by float numbers.

I have pretty much everything sorted up to convert the lines in

5条回答
  •  旧时难觅i
    2020-12-06 04:25

    I would use regular expressions

    import re

    all_lines = ''.join( file.readlines() )
    
    new_array = np.array( re.findall('[\d.E+-]+', all_lines), float)
    
    np.reshape( new_array, (m,n) )
    

    First merging the files into one long string, and then extracting only the expressions corresponding to floats ( '[\d.E+-]' for scientific notation, but you can also use '[\d.]' for only float expressions).

提交回复
热议问题