2016-10-14 2 views
0

나는이 문제가 해결되어야하는 포럼에서이 문제를 발견했다 : 당신은 일련의 통행이 주어질 것이고, 텍스트 (공백으로 구분 된 순서 단어들)은 하나 또는 그 이상의 다른 구절의 하위 구절로 전체적으로 포함되어있다.문자열 소거를위한 반복문을 통해 반복하기

봉쇄를위한 비교할 때, 특정 규칙을 따라야합니다

: 연속 공백의 다른 블록을 하나의 공간으로 처리해야 알파벳 문자의 경우는 선행 및 후행 공백 을 무시해야 이 을 무시해야 영숫자가 아닌 문자는 무시해야하며 공백은 그대로 두어야합니다. 중복 또한 필터링해야합니다. 위에서 열거 한 비교 규칙과 비교하여 두 개의 구절이 같은 것으로 간주되면 가장 짧은 값만 유지해야합니다. 길이가 같으면 입력 순서의 첫 번째 문자를 유지해야합니다. 유지 된 통로는 원래 형태 (입력 통로와 동일)와 같은 순서로 출력되어야합니다.

입력 1 : IBM 인식 컴퓨팅 | IBM "인식"컴퓨팅은 혁명입니다. ibm인지 컴퓨팅 | 'IBM인지 컴퓨팅'은 혁명인가? IBM "인지"컴퓨팅 :

출력 1 : | | IBM은 "인지"컴퓨팅은 혁명인지 컴퓨팅 혁명이다

출력 2 IBM인지 컴퓨팅 : IBM은 "인지"컴퓨팅 혁명

입력 2입니다 혁명이 |인지 컴퓨팅은

내가 파이썬에서 다음 코드를 쓴 혁명이지만, 그것은 첫 번째 테스트 케이스보다는 좀 다른 출력을주고 :

f = open("input.txt",'r') 
s = (f.read()).split('|') 
str = '' 
for a in s: 
    for b in s: 
     if(''.join(e for e in a.lower() if e.isalnum()))not in (''.join(e for e in b.lower() if e.isalnum())): 
      str = a.translate(None, "'?") 

print str 

input.txt에는 첫 번째 테스트 케이스 입력이 들어 있습니다. 출력을 다음과 같이 출력합니다. IBM인지 컴퓨팅은 혁명입니다. 누군가가 차임하고 나를 도와 줄 수 있습니까? 감사합니다

답변

0

나는 문자 그대로이 코드를 작성했습니다. 잘하면 이해하기 쉽습니다. 속도를 높이거나 질문이있는 경우 알려주십시오.

BTW, 이것은 파이썬 3 단지 print 문에서 괄호를 제거하고이 당신을 도와 경우 2.

import re 

def clean_input(text): 
    #non-alphanumeric character should be ignored 
    text = re.sub('[^a-zA-Z\s]', '', text) 
    #Any other block of contiguous whitespace should be treated as a single space 
    #white space should be retained 
    text = re.sub(' +',' ',text) 
    #Leading and trailing whitespace should be ignored 
    text = text.strip(' \t\n\r') 
    # You probably want this too 
    text = text.lower() 
    return text 

def process(text): 
    #If they are also the same length, the earlier one in the input sequence should be kept. 
    # Using arrays (can use OrderedDict too, probably easier and nice, although below is clearer for you. 
    original_parts = text.split('|') 
    clean_parts = [clean_input(x) for x in original_parts] 
    original_parts_to_check = [] 
    ignore_idx = [] 
    for idx, ele in enumerate(original_parts): 
     if idx in ignore_idx: 
      continue 
     #The case of alphabetic characters should be ignored 
     if len(ele) < 2: 
      continue 
     #Duplicates must also be filtered -if two passages are considered equal with respect to the comparison rules listed above, only the shortest should be retained. 
     if clean_parts[idx] in clean_parts[:idx]+clean_parts[idx+1:]: 
      indices = [i for i, x in enumerate(clean_parts) if x == clean_parts[idx]] 
      use = indices[0] 
      for i in indices[1:]: 
       if len(original_parts[i]) < len(original_parts[use]): 
        use = i 
      if idx == use: 
       ignore_idx += indices 
      else: 
       ignore_idx += [x for x in indices if x != use] 
       continue 
     original_parts_to_check.append(idx) 
    # Doing the text in text matching here. Depending on size and type of dataset, 
    # Which you should test as it would affect this, you may want this as part 
    # of the function above, or before, etc. If you're only doing 100 bits of 
    # data, then it doesn't matter. Optimize accordingly. 
    text_to_return = [] 
    clean_to_check = [clean_parts[x] for x in original_parts_to_check] 
    for idx in original_parts_to_check: 
     # This bit can be done better, but I have no more time to work on this. 
     if any([(clean_parts[idx] in clean_text) for clean_text in [x for x in clean_to_check if x != clean_parts[idx]]]): 
      continue 
     text_to_return.append(original_parts[idx]) 
    #The retained passages should be output in their original form (identical to the input passage), and in the same order. 
    return '|'.join(text_to_return) 

assert(process('IBM cognitive computing|IBM "cognitive" computing is a revolution| ibm cognitive computing|\'IBM Cognitive Computing\' is a revolution?') == 
     'IBM "cognitive" computing is a revolution') 
print(process('IBM cognitive computing|IBM "cognitive" computing is a revolution| ibm cognitive computing|\'IBM Cognitive Computing\' is a revolution?')) 
assert(process('IBM cognitive computing|IBM "cognitive" computing is a revolution|the cognitive computing is a revolution') == 
     'IBM "cognitive" computing is a revolution|the cognitive computing is a revolution') 
print(process('IBM cognitive computing|IBM "cognitive" computing is a revolution|the cognitive computing is a revolution')) 
또한

, 얻을 좋은 것 그것은 복사 및 붙여 넣기와 파이썬에 대한 실행됩니다 어떤 점, 그래서 받아 들일 것이 좋을 것이다 :) (나는 당신이 여기에서 새로운 것을 본다).

+1

감사합니다. 다시 한 번 감사드립니다. – GoRion