0

질문 제목을 적절하게 입력했는지 확실하지 않습니다. 그러나 아래의 문제를 설명하려고 노력했습니다. 이 문제를 생각할 수있는 경우 적절한 제목을 제안하십시오. 나는 list in the headerattribute in the attri_values의 일치를 기반으로 테이블을 만들려고 노력하고두 목록 간의 일치를 찾고 일치 항목을 기반으로 출력을 작성하는 방법은 무엇입니까?

list_headers = ['gene_id', 'gene_name', 'trans_id'] 
# these are the features to be mined from each line of `attri_values` 

attri_values = 

['gene_id "scaffold_200001.1"', 'gene_version "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"'] 
['gene_id "scaffold_200001.1"', 'gene_version "1"', 'trans_id "scaffold_200001.1"', 'transcript_version "1"', 'exon_number "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200001.1.exon1"', 'exon_version "1"'] 
['gene_id "scaffold_200002.1"', 'gene_version "1"', 'trans_id "scaffold_200002.1"', 'transcript_version "1"', 'exon_number "3"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200002.1.exon3"', 'exon_version "1"'] 

:

내가 목록 두 가지 유형의 데이터를 말해봐.

output = open('gtf_table', 'w') 
output.write('\t'.join(list_headers) + '\n') # this will first write the header 

# then I want to read each line 
for values in attri_values: 
    for list in list_headers: 
     if values.startswith(list): 
      attr_id = ''.join([x for x in attri_values if list in x]) 
      attr_id = attr_id.replace('"', '').split(' ')[1] 
      output.write('\t' + '\t'.join([attr_id])) 

     elif not values.startswith(list): 
      attr_id = 'NA' 
      output.write('\t' + '\t'.join([attr_id])) 

     output.write('\n') 

문제 :list of list_headers에서 일치하는 문자열이 values of attri_values에서 발견되면 모든 것이 잘 작동하지만, 일치가없는 경우 반복 'NA'가 많이있다.

최종 예상 결과 :

gene_id gene_name trans_id 
scaffold_200001.1 NA NA 
scaffold_200001.1 NA scaffold_200001.1 
scaffold_200002.1 NA scaffold_200002.1 

포스트 편집 : 내가 쓴 방법에 이 문제를 내 elif (때문에 모든이가 'NA'을 쓸 것 이외의 일치를 위해).NA의 상태를 다른 방법으로 옮기려고했지만 성공하지 못했습니다. 나는 elif을 제거 경우는 (NA가 손실)로 출력 번째 얻을 :

gene_id gene_name trans_id 
scaffold_200001.1 
scaffold_200001.1 scaffold_200001.1 
scaffold_200002.1 scaffold_200002.1 

답변

1

파이썬은 각 attri_values에 대한 각 목록 헤더를 반복하는 데 사용할 수있는 문자열에 대한 find 방법이있다. 이 기능을 사용해보십시오 :

def Get_Match(search_space,search_string): 
    start_character = search_space.find(search_string) 

    if start_character == -1: 
     return "N/A" 
    else: 
     return search_space[(start_character + len(search_string)):] 

for i in range(len(attri_values_1)): 
    for j in range(len(list_headers)): 
     print Get_Match(attri_values_1[i],list_headers[j]) 
1

내 대답 사용 팬더

import pandas as pd 

# input data 
list_headers = ['gene_id', 'gene_name', 'trans_id'] 

attri_values = [ 
['gene_id "scaffold_200001.1"', 'gene_version "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"'], 
['gene_id "scaffold_200001.1"', 'gene_version "1"', 'trans_id "scaffold_200001.1"', 'transcript_version "1"', 'exon_number "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200001.1.exon1"', 'exon_version "1"'], 
['gene_id "scaffold_200002.1"', 'gene_version "1"', 'trans_id "scaffold_200002.1"', 'transcript_version "1"', 'exon_number "3"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200002.1.exon3"', 'exon_version "1"']] 

# process input data 
attri_values_X = [dict([tuple(b.split())[:2] for b in a]) for a in attri_values] 

# Create DataFrame with the desired columns 
df = pd.DataFrame(attri_values_X, columns=list_headers) 

# print dataframe 
print df 

출력 팬더없이

   gene_id gene_name    trans_id 
0 "scaffold_200001.1"  NaN     NaN 
1 "scaffold_200001.1"  NaN "scaffold_200001.1" 
2 "scaffold_200002.1"  NaN "scaffold_200002.1" 

뿐만 아니라 간단합니다. 나는 이미 당신에게 attri_values_X을주었습니다. 그리고 거의 다 왔었습니다. 원하지 않는 사전에서 키를 제거하십시오.

1

데이터를 구문 분석하는 데 유용한 함수를 작성했습니다.

def searchHeader(title, values): 
    """" 
    searchHeader(title, values) --> list 

    *Return all the words of strings in an iterable object in which title is a substring, 
    without including title. Else write 'N\A' for strings that title is not a substring. 
    Example: 
      >>> seq = ['spam and ham', 'spam is awesome', 'Ham is...!', 'eat cake but not pizza'] 
      >>> searchHeader('spam', attri_values) 
      ['and', 'ham', 'is', 'awesome', 'N\\A', 'N\\A'] 
    """ 
    res = [] 
    for x in values: 
     if title in x: 
      res.append(x) 
     else: 
      res.append('N\A')      # If no match found append N\A for every string in values 

    res = ' '.join(res) 
    # res = res.replace('"', '')     You can use this for your code or use it after you call the function on res 
    res = res.split(' ') 
    res = [x for x in res if x != title]   # Remove title string from res 
    return res 

: 나는 어쨌든 내가 판단 할 수있는 위치에 아니에요 당신은 구문 분석해야 할 데이터를 저장하는 방법을 여기에 문제를 복잡하게 무엇 당신이 게시 된 원래의 코드를 수정하려고 여기 내 코드입니다 이런 경우에도 정규식을 사용하면 편리합니다. 이 함수로 데이터를 구문 분석 한 다음 결과를 형식화하여 파일에 테이블을 작성하십시오. 이 함수는 하나의 for 루프와 하나의 목록 이해를 사용하며 코드에서 두 개의 중첩 된 for 루프와 하나의 목록 이해를 사용합니다.

처럼, 함수에 개별적으로 각각의 헤더 문자열을 전달 다음이 가능하면

for title in list_headers: 
    result = searchHeader(title, attri_values) 
    ...format as table... 
    ...write to file... 

은, 당신의 attri_values에 대한 사전에 간단한 목록에서 이동 그룹화하여 문자열과 함께 할 수있는 방법을 고려 헤더 :

attri_values = {'header': ('data1', 'data2',...)} 

제 생각에는 목록을 사용하는 것보다 낫습니다. 또한 코드에서 list 이름을 재정의하는 것은 좋은 일이 아니므로 list 실제로 목록을 만드는 내장 클래스이기 때문입니다.

+0

답변 해 주셔서 감사합니다. 사전을 사용하면 큰 데이터의 일부에 지나지 않기 때문에 복잡합니다. 간단한 for-loop로 해결할 수 있다고 생각했습니다. Btw,'result = searchHeader (list_headers, attri_values)'에 유형 오류가 발생했습니다. – everestial007

+0

@ everestial007 나쁜 소식! 나는 함수에'list_headers' 대신'title'을 넘겨 줘야했습니다 :'result = searchHeader (title, attri_values)'. 늦은 밤에 코드 작성의 결과가 될 수 있습니까? P? – direprobs

+0

나는 컴퓨터에 너무 많은 정보를 보내거나 졸린 결과를 이해합니다. Btw, 코드는 여전히 나를 위해 문제를 해결할 수 없습니다. 나는 x와 같은 뭔가를 바꾸려고 시도했다.'x에있는 제목 :'나는 그것이''x.startswith (title)'이면 모든 문자열이 일치하지 않는 한 비교 목록에 히트가 없을 이유가 있어야한다고 생각한다. *. 나도 다른 일들을 바꿔 보려고했지만 행운은 없었어. 나에게 완벽한 예제를 주시겠습니까? - 그렇게 될 수 있습니다. 이 질문에 너무 많은 관심을 너무 upvote하시기 바랍니다. – everestial007