3 回答

TA貢獻1864條經驗 獲得超2個贊
我還想建議一個使用 difflib 的解決方案,但我更喜歡使用 RegEx 進行單詞檢測,因為它會更精確并且更能容忍奇怪的字符和其他問題。
我在您的原始字符串中添加了一些奇怪的文字以表明我的意思:
import re
import difflib
truth = 'The quick! brown - fox jumps, over the lazy dog.'
speech = 'the quick... brown box jumps. over the dog'
truth = re.findall(r"[\w']+", truth.lower())
speech = re.findall(r"[\w']+", speech.lower())
for d in difflib.ndiff(truth, speech):
print(d)
輸出
the
quick
brown
- fox
+ box
jumps
over
the
- lazy
dog
另一個可能的輸出:
diff = difflib.unified_diff(truth, speech)
print(''.join(diff))
輸出
---
+++
@@ -1,9 +1,8 @@
the quick brown-fox+box jumps over the-lazy dog

TA貢獻1876條經驗 獲得超6個贊
為什么不將句子拆分成單詞然后在這些單詞上使用 difflib?
import difflib
truth = 'The quick brown fox jumps over the lazy dog.'.lower().strip(
'.').split()
speech = 'the quick brown box jumps over the dog'.lower().strip('.').split()
for d in difflib.ndiff(truth, speech):
print(d)

TA貢獻1963條經驗 獲得超6個贊
所以我想我已經解決了這個問題。我意識到 difflib 的“contextdiff”提供了其中有變化的行的索引。為了獲取“ground truth”文本的索引,我刪除了大寫/標點符號,將文本拆分為單個單詞,然后執行以下操作:
altered_word_indices = []
diff = difflib.context_diff(transformed_ground_truth, transformed_hypothesis, n=0)
for line in diff:
if line.startswith('*** ') and line.endswith(' ****\n'):
line = line.replace(' ', '').replace('\n', '').replace('*', '')
if ',' in line:
split_line = line.split(',')
for i in range(0, (int(split_line[1]) - int(split_line[0])) + 1):
altered_word_indices.append((int(split_line[0]) + i) - 1)
else:
altered_word_indices.append(int(line) - 1)
在此之后,我將更改后的單詞大寫打印出來:
split_ground_truth = ground_truth.split(' ')
for i in range(0, len(split_ground_truth)):
if i in altered_word_indices:
print(split_ground_truth[i].upper(), end=' ')
else:
print(split_ground_truth[i], end=' ')
這讓我可以打印出“The quick brown FOX jumps over the LAZY dog”。(包括大寫/標點符號)而不是“快速的棕色 FOX 跳過 LAZY 狗”。
這不是一個超級優雅的解決方案,它需要經過測試、清理、錯誤處理等。但這似乎是一個不錯的開始,并且可能對遇到相同問題的其他人有用。我會把這個問題懸而未決幾天,以防有人想出一種不太粗略的方法來獲得相同的結果。
添加回答
舉報