2015-02-03 3 views
0

.csv 파일을 읽고 csvfile이라는 행렬에 저장하면 매트릭스 내용이 다음과 같이 보입니다 (축약 된 수십 개의 레코드가 있습니다.)파일의 문자열이 문자열 목록에 있는지 확인하십시오. python

[ '411-440854-0', '411-440824-0', '411-441232-0」, 「394-529791」, 「394-529729」, 「394-530626 '], < ...>'[394-1022430-0 ','394-1022432-0 ','394-1022432-0 ','*** 사이에 스위치가있는 다른 CN '], [' 394-833938-0 ','394-833940-0 '], < ...>, ['394-1021830-0 ','394-1021831-0 ','394-833938-0 ','394-833940-0 ' 1021832-0 ','*** 단면 구분자 연결 '], ['394-1022736-0 ','394-1022737-0 ','394-1022738-0 '], < ...>, [ '394-1986420-0', '394-1986419-0', '394-1986416-0', '*** 별난 BN 줄 확인'], [ '394-1986411-0', '394-1986415-0', '394-1986413-0'], <>, [ '394-529865-0', '394-529686-0', '394-530875-0', '*' ** 단면 절단기 연결 '], ['394-830900-0 ','394-830904-0 ','394-830902-0 '], ['394-2350772-0 ','394-2350776-0 ' '394-2350774-0', '*** 현재 섹하지만 최종 휴식', < ...>]

내가 textfile라는 변수에 텍스트 파일 및 컨텐츠 외모를 읽고있다 좋아요 :

... 
object underground_line { 
    name SPU123-394-1021830-0-sectionalizer; 
    phases AN; 
    from SPU123-391-670003; 
    to SPU123-395-899674_sectionalizernode; 
    length 26.536; 
    configuration SPU123-1/0CN15-AN; 
} 

object underground_line { 
    name SPU123-394-1021831-0-sectionalizer; 
    phases BN; 
    from SPU123-391-670002; 
    to SPU123-395-899675_sectionalizernode; 
    length 17.902; 
    configuration SPU123-1/0CN15-BN; 
} 

object underground_line { 
    name SPU123-394-1028883-0-sectionalizer; 
    phases CN; 
    from SPU123-391-542651; 
    to SPU123-395-907325_sectionalizernode; 
    length 771.777; 
    configuration SPU123-1CN15-CN; 
} 
... 

name 부분을보고 싶습니다. 행 textfile (SPU123- 이후이고 -0-sectionalizer 전의 행)은 csvfile 행렬에 있습니다. 그것이 존재하지 않으면, 나는 무언가를하고 싶다. (카운터를 증가시킨다.) 아래를 포함한 몇 가지 방법을 시도했다 :

counter = 0 
for noline in textfile: 
    if 'name SPU123-' in noline: 
     if '-' in noline[23]: 
      if ((noline[13:23] not in s[0]) and (noline[13:23] not in s[1]) and (noline[13:23] not in s[2]) for s in csvfile): 
       counter = counter+1 
     else: 
      if ((noline[13:24] not in s[0]) and (noline[13:24] not in s[1]) and (noline[13:-24] not in s[2]) for s in csvfile): 
       counter = counter+1 
print counter 

이것은 작동하지 않는다. 또한 위의 코드 예제에서 if any((noline......)으로 시도했지만 작동하지 않습니다. (noline[13:23]이가 검색하고자하는 문자열이 있다고 가정하고,이에없는 경우 다음 counter을 증가 코드에이 구현

>>> l = [['str', 'foo'], ['bar', 'so']] 

>>> s = 'foo' 
>>> any(s in x for x in l) 
True 

>>> s = 'nope' 
>>> any(s in x for x in l) 
False 

: l 목록의 목록에서 문자열 s 점검

+0

'''textfile'''에 매트릭스의 항목보다 더 많은 것이 있습니까? 행렬은 목록의 목록 일뿐입니다? – wwii

+0

@wwii 방금'print csvfile' 출력으로 질문을 편집했습니다. 'textfile'은 제가 질문에서 보여준 것보다 훨씬 많은 것을 가지고 있습니다. 이것은 전체 파일의 작은 조각 일뿐입니다. 각'이름'(질문에서 설명한대로 특정 인덱스 사이에 있음)을'csvfile' 행렬 –

답변

1

csvfile) : 당신의 행렬 값의 부하에 따라 부하를 포함

counter = 0 
for noline in textfile: 
    if 'name SPU123-' in noline: 
     if '-' in noline[23]: noline[13:23]: 
      if not any(noline[13:23] in x for x in csvfile) and not any(noline[13:23] + '-0' in x for x in csvfile): 
       counter += 1 
     else: 
      if not any(noline[13:24] in x for x in csvfile) and not any(noline[13:24] + '-0' in x for x in csvfile): 
       counter += 1 
+0

에서 확인하려고합니다. 작동하지 않습니다. 예를 들어'any ('csvfile에서 x에 대해 x에 대해 394-1260252')를 시도하고'True '대신'False'를 생성했습니다. –

+0

'csvfile'은 위의 모양대로 구성되지 않을 수 있습니다 ... 인쇄 할 수 있습니까? csvfile'을 실행하고 결과를 보여줍니다. – Jkdc

+0

'print csvfile' 내용으로 질문을 편집했습니다. –

1

때문에, 그 위에 모든마다 반복하는 것은 매우 느리다. (연관된 데이터가 없기 때문에이 경우에는 set)를 해시 테이블 조회가 매우 빠르고 때문에

대신 매핑으로 값을 조립 :

s = {v for r in matrix for v in r if re.match(r'\d[-\d]+]\d$',v)} #or any filter more appropriate for your notion of valid identifiers 

if noline[13:23] in s: #parsing the identifiers instead would be more fault-tolerant 
    #do something 

예비 단계로, 이것은 단지 능가 시작됩니다 인해 특정 규모를 초월한 무차별 적 접근.

data_rex = re.compile(r'\d{3}-\d+') 
data = {match.group() for match in itertools.imap(data_rex.match, data) if match} 

정량화 (여러 번 데이터의 반복을 피하기) data

data = itertools.chain.from_iterable(csvfile) 

추출 관련 항목 데이터에서 반복자이며, 성능을 위해 그것을 집합을 -

0
import re, itertools 

csvfile가 평평 데이터에없는 이름.

def predicate(match, data = data): 
    '''Return True if match not found in data''' 
    return match.group(1) not in data 

# after SPU123- and before -0- 
name = re.compile(r'name SPU123-(\d{3}-\d+)-') 
names = name.finditer(textfile) 
# quantify 
print sum(itertools.imap(predicate, names)) 
관련 문제