2013-01-06 8 views
0

목록의 요소를 검사 할 수 있습니까? "test01.txt"와 같은 단어가 있으면 공백으로 바꿉니 까?목록의 요소를 공백으로 바꿉니다.

test01.txt : 코드에서

to 
her 
too 
a 
for 

: "인쇄 SSX"에서

with open('C:/test01.txt') as words: 
    ws = words.read().splitlines() 
with open('C:/test02.txt') as file_modify4: 
    for x in file_modify4: 
     sx = map(str.strip, x.split("\t")) 
     ssx = sx[0].split(" ") 
     print ssx 

결과 :

['wow'] 
['listens', 'to', 'her', 'music'] 
['too', 'good'] 
['a', 'film', 'for', 'stunt', 'scheduling', 'i', 'think'] 
['really', 'enjoyed'] 

어떻게 SSX의 요소를 대체?

['wow'] 
['listens', ' ', ' ', 'music'] 
[' ', 'good'] 
[' ', 'film', ' ', 'stunt', 'scheduling', 'i', 'think'] 
['really', 'enjoyed'] 

어떤 제안 :

는 결과를 예상?

답변

3

목록 사용; 완벽한 솔루션으로,

ws = set(ws) 

# ... 
    ssx = [w if w not in ws else ' ' for w in ssx]  

또는 : 먼저 빠른 테스트 세트에있는 단어를 저장

with open('C:/test01.txt') as words: 
    ws = set(words.read().splitlines()) 

with open('C:/test02.txt') as file_modify4: 
    for x in file_modify4: 
     ssx = [w if w not in ws else ' ' for w in x.strip().split('\t')[0].split()] 
     print ssx 
1

순진 솔루션입니다 : 물론

new_ssx = [] 
for word in ssx: 
    if word in ws: 
     new_ssx.append(' ') 
    else: 
     new_ssx.append(word) 

당신이있을 때마다 빈 목록을 방금 루프에 추가하면 목록 이해로 바꿀 수 있습니다.

new_ssx = [' ' if word in ws else word for word in ssx] 

ws이 몇 단어 이상이면 조회를 더 빨리 수행하려면 set으로 바꾸는 것이 좋습니다.

with open('C:/test01.txt') as words: 
    ws = set(words.read().splitlines()) 
with open('C:/test02.txt') as file_modify4: 
    for x in file_modify4: 
     sx = map(str.strip, x.split("\t")) 
     ssx = sx[0].split(" ") 
     new_ssx = [' ' if word in ws else word for word in ssx] 
     print new_ssx 
+0

는 초 나를 이길 : 모두 함께 넣어 그래서

, D –

관련 문제