2016-12-06 65 views
-1

我遇到了编写python脚本的麻烦。具体来说,我有一串数字,并希望用整数0替换单词“零”。然后,我想将此字符串覆盖为浮点值。我使用了data.replace,因此必须在“0”周围放置“ - ”,否则会出现错误,因为它需要字符缓冲区对象。我是否正确地说我可以在转换为浮点数之前从0中除去“”?将字符串转换为浮点时出错

> for data in inFile: 
> data = data.replace ("zero", "0") 

> data = map(float,data.strip('"'))                

ValueError: could not convert string to float: s

这是一个较大的脚本,这需要在值的列表的一部分。我想从第一100

inFile = gzip.open('path','rb') 

inpNorm = 0.5 
samNorm = 1 

inFile.next() 
for line in inFile: 
     cols = line.strip().split('\t') 
     data = cols[6:] 
     for data in inFile: 
       data = data.replace("zero",0) 
     data = map(float,data.strip('"')) 

     inputVals = [x * inpNorm for x in data[:100]] 
     h3k27Vals = [x * samNorm for x in data[100:]] 

     normVals = [h327Vals[i] - inputVals[i] for i in len(inputVals)] 

     print '\t'.join(cols[:6]) + '\t'.join(map(str,normVals)) 

inFile.close() 

我输入文件看起来像下面减去该列表的最后100个值对于给定线:

C8098283  1  8268 asx1.1_ox1.0.loc.00001 .  + zero zero zero 11.701 12.801 13.91 

非常感谢

附:真的很抱歉,如果这不够明确。我对编程和堆栈溢出很陌生。

+2

显示示例输入 –

+0

好像你在你的数据文件中有杂散的字符。 – Iluvatar

+0

你能更清楚的转换吗?您需要不剥去''' –

回答

0

这里有一些建议。

line = "8268 asx1.1_ox1.0.loc.00001 .  + zero zero zero 11.701 12.801 13.91" 
print("Input: '{}'".format(line)) 

converted_line = "0".join(line.split('zero')) # Split the line where you have 'zero' and rebuild the string with '0' 
print("Converted line: '{}'".format(converted_line)) 

你说你想转换的价值。行中有几个非浮点条目,但最后6个值似乎很有趣。我通常通过解压缩值:

v1, v2, v3, v4, v5, v6 = map(float, converted_line.rstrip().split()[4:]) 
# .split() with no argument splits on whitespace 
# .rstrip() is to remove trailing '\n' (newlines), which are common when parsing files 
print("Data:", v1, v2, v3, v4, v5, v6) 

当然,你可以将它存储在一个阵列以及(即data = map(float, converted ...))。运行它一起产生输出

Input: '8268 asx1.1_ox1.0.loc.00001 .  + zero zero zero 11.701 12.801 13.91' 
Converted line: '8268 asx1.1_ox1.0.loc.00001 .  + 0 0 0 11.701 12.801 13.91' 
Data: 0.0 0.0 0.0 11.701 12.801 13.91 

此外,为了解决你的实际问题。现在你想要从文件的不同位置读取对方的内容(即你想去0 -> 100, 1 -> 101, 2 -> 102等)。这有点麻烦,而且效率不高。如果你的文件大小不是太大(可能是< 1M行),我建议你阅读整个文件,进行计算,然后根据数据做你想做的事情。类似于

col1 = [] 
col2 = [] 
... 

for line in file.readlines(): 
    v1, v2, ... = map(float, converted_line.rstrip().split()[...]) 
    col1.append(v1) 
    col2.append(v2) 
    ... 

# Now do your data manipulation of the parsed data that you find in `col1`, `col2`, etc