I have a list of objects "repeated_words_list" & each object contains a dictionary having a word(string), start(float), end(float), conf(float)
I want to keep only 1 occurrence of each repeated word that has the highest p.start among all of its occurrences and remove all occurrences with lower p.start.
I have printed it like this
for p in repeated_words_list:
print(f"{p.word} {p.start} - {p.end}")
Output
p.word p.start - p.end
the 0.27 - 2.91
the 25.38 - 25.5
the 26.94 - 27.24
the 27.66 - 27.81
the 38.67 - 38.705229
the 53.22 - 53.73
the 55.02 - 55.17
well 2.91 - 3.39
well 3.96 - 4.38
well 5.82 - 6.09
well 9.09 - 9.42
well 12.21 - 12.63
keeping 4.53 - 4.95
keeping 13.2 - 13.53
yourself 4.95 - 5.43
yourself 13.53 - 14.04
it 6.09 - 6.24
it 56.67 - 56.88
can 6.24 - 6.57
can 21.09 - 21.48
is 15.81 - 16.05
is 25.86 - 26.04
is 28.14 - 28.26
a 16.05 - 16.14
a 22.862336 - 22.89
see 54.764476 - 55.02
whether 61.35 - 61.71
whether 63.63 - 63.93
it's 61.71 - 62.07
it's 63.93 - 64.17
I tried this way but couldn't get this done since I am not able to access previous and next element.
for i in range(len(repeated_words_list)):
if p[i].word == p[i-1].word:
if p[i].start > p[i-1].start:
repeated_words_list[i-1]= p[i].start
can some good soul guide me for this? Thanks in advance!
CodePudding user response:
Create a dictionary which uses word
as an index. If the index already exists, update the value only if a higher start
value is found.
final_words = {}
for p in repeated_words_list:
word = final_words.get(p.word, None)
if not word:
final_words[p.word] = p
else:
if word.start < p.start:
final_words[p.word] = p
# to get highest values
for p in final_words.values():
print(f"{p.word} {p.start} - {p.end}")
# for all words other than the one with highest occurence
for p in repeated_words_list:
if final_words[p.word] != p:
print(f"{p.word} {p.start} - {p.end}")