이 솔루션은 txt
문자열 내에서 N- 그램의 모든 사본을 찾기 위해 str.find
방법을 사용하기 때문에 우리가 쉽게 경기를 중복 처리 할 수있는 설정 indices
각 사본의 인덱스를 저장 .
그런 다음 txt
char 문자를 result
목록에 복사하고 필요한 경우 꺾쇠 괄호를 삽입하십시오. 이 전략은 각 .replace
호출이 전체 문자열을 다시 작성해야하기 때문에 복수 .replace
호출을 사용하여 꺾쇠 괄호를 삽입하는 것보다 효율적입니다.
내 코드가 ngram의 여러 복사본을 처리한다는 것을 보여주기 위해 데이터를 약간 확장했습니다.
how does this work now chisolm
['ow ', 'his', 's w']
ow 1
ow 20
his 10
his 24
s w 12
{1, 2, 10, 11, 12, 13, 20, 21, 24, 25}
h<ow >does t<his w>ork n<ow >c<his>olm
당신이 인접 그룹을 병합하려면
txt = "how does this work now chisolm"
ngrams = ["ow ", "his", "s w"]
print(txt)
print(ngrams)
# Search for all copies of each ngram in txt
# saving the indices where the ngrams occur
indices = set()
for s in ngrams:
slen = len(s)
lo = 0
while True:
i = txt.find(s, lo)
if i == -1:
break
lo = i + slen
print(s, i)
indices.update(range(i, lo-1))
print(indices)
# Copy the txt to result, inserting angle brackets
# to show matches
switch = True
result = []
for i, u in enumerate(txt):
if switch:
if i in indices:
result.append('<')
switch = False
result.append(u)
else:
result.append(u)
if i not in indices:
result.append('>')
switch = True
print(''.join(result))
출력, 우리는 쉽게 str.replace
방법을 사용하여 그렇게 할 수 있습니다. 그러나이 작업을 제대로 수행하려면 원본 데이터를 사전 처리해야하며 모든 공백을 단일 공백으로 변환해야합니다. 이를 수행하는 간단한 방법은 데이터를 분할하고 다시 참여시키는 것입니다.
txt = "how does this\nwork now chisolm hisow"
ngrams = ["ow", "his", "work"]
#Convert all whitespace to single spaces
txt = ' '.join(txt.split())
print(txt)
print(ngrams)
# Search for all copies of each ngram in txt
# saving the indices where the ngrams occur
indices = set()
for s in ngrams:
slen = len(s)
lo = 0
while True:
i = txt.find(s, lo)
if i == -1:
break
lo = i + slen
print(s, i)
indices.update(range(i, lo-1))
print(indices)
# Copy the txt to result, inserting angle brackets
# to show matches
switch = True
result = []
for i, u in enumerate(txt):
if switch:
if i in indices:
result.append('<')
switch = False
result.append(u)
else:
result.append(u)
if i not in indices:
result.append('>')
switch = True
# Convert the list to a single string
output = ''.join(result)
# Merge adjacent groups
output = output.replace('> <', ' ').replace('><', '')
print(output)
출력
how does this work now chisolm hisow
['ow', 'his', 'work']
ow 1
ow 20
ow 34
his 10
his 24
his 31
work 14
{32, 1, 34, 10, 11, 14, 15, 16, 20, 24, 25, 31}
h<ow> does t<his work> n<ow> c<his>olm <hisow>
대신 무엇이 생성됩니까? –
'ngrams = [ 'his', 's wo', 'wor']'가 있으면 어떻게 될 것인가. ' k는 어떻게 되는가? '를 기대하십니까? –
여러 경기를 처리하는 방법은 무엇입니까? 예 : 'ngrams = [ 'ab']','txt = 'abominable abs''. ' ominable abs', ' ominable s' 또는'abominable s'을 기대합니까? –