python - 从文本文件中删除字符串保持 float

标签 python string file

我想删除文本文件中带有字符串的行或空行。看起来像这样。如您所见,标题在整个文件中自行重复。每个 block 的数据行数各不相同。我需要它作为 numpy 中的数组导入。起初我用逗号表示小数点,至少我能够改变它。

我试过了,但根本不起作用:

from types import StringType

z = open('D:\Desktop\cycle 1-20 20-50 kPa (dot).dat', 'r')
for line in z.readlines():
    for x in z:
        if type(z.readline(x)) is StringType:
            print line


z.close()

数据示例:

bla bla

cyclical stuff                      Time:   81.095947   Sec 2012-08-02 17:05:42
stored :    1   cycle           stores for :    62  seg-cycle
Points :    4223
Servo_Hyd count Temps   Servo_Air pressure  Servo_Hyd load Servo_Hyd LVDT1  Servo_Hyd LVDT2 Servo_Hyd LVDT3
name1    name1    name1 name1   name1   name1   name1
1   60.102783   0.020013755 89.109558   0.3552089   0.4015148   -0.33822596
1   60.107666   0.020006953 89.025749   0.35519764  0.4015218   -0.33821729
1   60.112549   0.02000189  88.886292   0.3551946   0.4015184   -0.33822691
1   60.117432   0.020007374 89.559196   0.35519707  0.40151948  -0.33823174
1   60.122314   0.019991774 89.741402   0.35519552  0.40151322  -0.33822927
1   60.127197   0.020003742 89.748924   0.35520011  0.40150556  -0.33822462

bla bla

cyclical stuff                      Time:   81.095947   Sec 2012-08-02 17:05:42
stored :    1   cycle           stores for :    62  seg-cycle
Points :    4223
Servo_Hyd count Temps   Servo_Air pressure  Servo_Hyd load Servo_Hyd LVDT1  Servo_Hyd LVDT2 Servo_Hyd LVDT3
name1    name1    name1 name1   name1   name1   name1
1   60.102783   0.020013755 89.109558   0.3552089   0.4015148   -0.33822596
1   60.107666   0.020006953 89.025749   0.35519764  0.4015218   -0.33821729
1   60.112549   0.02000189  88.886292   0.3551946   0.4015184   -0.33822691
1   60.117432   0.020007374 89.559196   0.35519707  0.40151948  -0.33823174
1   60.122314   0.019991774 89.741402   0.35519552  0.40151322  -0.33822927
1   60.127197   0.020003742 89.748924   0.35520011  0.40150556  -0.33822462

最佳答案

除非您强制转换它们,否则 Python 最初会将所有文件元素读取为字符串,因此您的方法将不起作用。

最好的办法可能是使用正则表达式来过滤掉其中包含非数据字符的行。

f = open("datafile")
for line in f:
  #Catch everything that has a non-number/space in it
  if re.search("[^-0-9.\s]",line): 
     continue
  # Catch empty lines
  if len(line.strip()) == 0:
     continue
  # Keep the rest
  print(line)

f.close()

关于python - 从文本文件中删除字符串保持 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13686983/

相关文章:

vb.net - 在 vb.net 中输入文本字段解析器的字符串

java - 如何在 while 循环中读取以特殊字符串结尾的文件?

c++ - 在 vector 中按一个词查找行

html - 克隆 CSS 样式的文件上传按钮

python - 测试测试函数装饰器

python - 找到将 float 列表转换为整数列表的公因数

string - Haskell 中的类型类

Ruby - 如何检查字符串是否包含数组中的所有单词?

python - 如何去除尾随零的整数

ansible - 请解释此算法以获取字符串的所有排列