gpt4 book ai didi

python - 如果嵌套列表中的子列表部分匹配另一个嵌套列表中的子列表,则返回该子列表

转载 作者:太空宇宙 更新时间:2023-11-03 20:36:48 26 4
gpt4 key购买 nike

我有一个英语词频列表,其中包括单词、其词性 (POS) 及其频率,位于嵌套列表中

freq_list = 
[['such', 'JJ', '17930'],
['year', 'NN', '17920'],
['as', 'RB', '17107']]

我还有一个嵌套的标记列表,其中包含单词和 POS。

tokens = 
[['legend', 'NN'],
['of', 'IN'],
['zelda', 'NN']]

我想比较列表,如果 token 中的单词和词性在 freq_list 中,我想将 freq_list 中的最后一个值附加到 token 中。


def get_frequency(self, tokens, freq_list):
self.__frequencies = []
for token in self.tokens:
if token[0] in [item[0] for item in self.freq_list] and
token[1] in [item[1] for item in self.freq_list]]:
freq = token, self.freq_list(i)

我正在努力处理最后一行,它定义了频率。我希望它是来自 token 的单词和 POS(或者来自 freq_list,它们应该是相同的)以及来自 freq_list 的相应频率。任何建议都会很棒。

此外,我需要使用 if 语句,因为还需要满足其他两个条件(例如,如果 self.freq_list 中存在 token[0],并且 token[0] 和 token[1] 都不存在。

最佳答案

您可能最好使用字典而不是嵌套列表来对此进行建模:

freqs = {}
for word, pos, f in freq_list:
if word not in freqs: freqs[word] = {}
freqs[word][pos] = f

for i, (word, pos) in enumerate(tokens):
if word not in freqs:
tokens[i].append(0) # fix for scenario #2
continue
if pos not in freqs[word]: # fix for scenario #1
pos = "UNK"
if pos not in freqs[word]: continue
tokens[i].append(freqs[word][pos])
continue
tokens[i].append(freqs[word][pos])

关于python - 如果嵌套列表中的子列表部分匹配另一个嵌套列表中的子列表,则返回该子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57113704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com