をこのソリューションは、我々は簡単に試合を重ねる処理できるようindices
セットに各コピーのインデックスを保存し、txt
文字列内のnグラムのすべてのコピーを見つけるためにstr.find
メソッドを使用しています。
次に、txt
のcharによる文字をresult
リストにコピーし、必要な場合は角かっこを挿入します。この方法は、.replace
コールが複数の文字列全体を再構築する必要があるため、複数の.replace
コールを使用して山括弧を挿入するよりも効率的です。
私のコードがngramの複数のコピーを処理することを示すためにデータを少し拡張しました。
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))
出力
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
あなたは隣接するグループをマージしたい場合は、我々は簡単に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'を期待していますか? –