2014-10-01 169 views
1

在我的代碼上有問題。 我得到這個AttributeError,我不知道爲什麼。 有人提供一點點洞察力,謝謝! 這是用python 3寫的, 我正在試圖製作一個圖表。AttributeError:'str'對象沒有屬性'readlines'

import sys 
data = {} 
def main(): 
    filename = sys.argv[1] 
    parseFile(filename) 
    function()  
def parseFile(fn): 
    print("Parsing", fn) 
    infile = open(fn, "r") 
    for line in infile: 
     line = line[:-1] 
     tokens = line.split() 
     print(tokens) 
     if line[0]=="#": 
      line.readline() #<-- this is my problem line 
     rsid = (tokens[0]) 
     genotype = (tokens[3]) 
     data[rsid] = genotype 
    infile.close() 
main() 

# This data file generated by 23andMe at: Wed Jan 26 05:37:08 2011 
# 
# Below is a text version of your data. Fields are TAB-separated 
# Each line corresponds to a single SNP. For each SNP, we provide its identifier 
# (an rsid or an internal id), its location on the reference human genome, and the 
# genotype call oriented with respect to the plus strand on the human reference 
# sequence.  We are using reference human assembly build 36. Note that it is possible 
# that data downloaded at different times may be different due to ongoing improvements 
# in our ability to call genotypes. More information about these changes can be found at: 
# https://www.23andme.com/you/download/revisions/ 
# 
# More information on reference human assembly build 36: 
# http://www.ncbi.nlm.nih.gov/projects/mapview/map_search.cgi?taxid=9606&build=36 
# 
# rsid chromosome position genotype 
rs4477212 1 72017 AA 
rs3094315 1 742429 AA 
rs1799883 1 742429 AA 
rs3131972 1 742584 GG 
rs12124819 1 766409 AA 
rs11240777 1 788822 GG 
rs6681049 1 789870 CC 
rs4970383 1 828418 CC 
rs4475691 1 836671 CC 
rs7537756 1 844113 AA 
+0

這是什麼語言?哪條線的確切錯誤是什麼?你有沒有試圖減少你的例子? – usr1234567 2014-10-01 05:48:05

+0

ahhh。對不起。蟒蛇。錯誤是在line.readline() 我試圖減少我的例子,但不是最好的這樣做 – Cooper 2014-10-01 05:49:07

+0

爲什麼你有line.readline()那裏?你的意圖是什麼? – user1269942 2014-10-01 05:58:01

回答

0

屬性錯誤意味着readline不是字符串方法。

在此片斷:

for line in infile: 
    line = line[:-1] 
    tokens = line.split() 

我猜測,線[: - 1](是否正確?)是剝離換行。如果是這種情況,請嘗試使用這種方法:

for line in infile: 
    line = line.strip() 
    tokens = line.split() 

帶鋼將剝離新線和回車。並且由於您只是將行更改爲僅包含換行符的文本,因此可以使用line.readline()刪除行。

更新: 跳過線的「跳過」,我把它意味着要忽略他們以#

for line in infile: 
    line = line.strip() 
    if line[0]=="#": 
     continue 
    tokens = line.split() 

開始。

也爲良好的狀態,你應該在你的parseFile功能行:

def parseFile(fn): 
    global data 
    ... 
+0

好的。我試圖跳過#。我剛剛更新了上面的代碼^^^以提供更多信息。 line.strip()命令是否仍然有效? – Cooper 2014-10-01 06:25:22

+1

在分割之前,不需要從線的末端去除空白。 ''1 2 4'.split()== ['1','2','4']'。 – 2014-10-02 06:03:46

+0

@特里你是對的,如果你在空間上分裂。無論我分開什麼東西(這很少是空格),我總是習慣於使用strip。 – user1269942 2014-10-02 07:22:51