如何在Lis中查找和统计元素集

2024-10-01 09:19:49 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我搜索并计算pos\uxist命名列表的代码,该列表包含en.wiktionary.org的已爬网元素。这个列表包含wiktionary可能的词性标签(不带pos),我搜索这个列表只是为了计算列表中有多少个词性标签。 如何以更简洁的方式缩短下面的代码

count = 0
        for i in range(0,10): #assumed maximum count of possible POS is 10
            try:
                if 'Noun' in pos_xist[i]:
                    count +=1
                elif 'Verb' in pos_xist[i]:
                    count +=1
                elif 'Pronoun' in pos_xist[i]:
                    count +=1
                elif 'Adjective' in pos_xist[i]:
                    count +=1
                elif '' in pos_xist[i]:
                    count +=1
                elif 'Pronoun' in pos_xist[i]:
                    count +=1
                elif 'Adverb' in pos_xist[i]:
                    count +=1
                elif 'Particle' in pos_xist[i]:
                    count +=1
                elif 'Conjunction' in pos_xist[i]:
                    count +=1
                elif 'Interjection' in pos_xist[i]:
                    count +=1
                elif 'Prepoisition' in pos_xist[i]:
                    count +=1
                elif 'Determiner' in pos_xist[i]:
                    count +=1
                elif 'Article' in pos_xist[i]:
                    count +=1
                else:
                    pass
            except:
                pass

Tags: 代码inpos列表countpass标签命名
3条回答
postaglist=['Noun','Verb'...]
for item in pos_xist:
    if item in postaglist:
        count=count+1

列出所有可能的pos标签并在其中搜索

您可以创建要搜索的单词列表,并使用生成器表达式迭代pos_xist中的每个项目:

words = ['Noun', 'Verb', 'Pronoun']
count = sum(any(word in item for word in words) for item in pos_xist)

如果要限制到前十项,请使用切片pos_xist[:10]

不需要异常处理

您可以将^{} builtin与每个项目的列表结合使用,而不是等到抛出错误

它看起来像这样

count = 0
words = ["Noun", "Verb", "Pronoun", ...]
for pos in pos_xist:
    if any(word in pos for word in words):
        count += 1

相关问题 更多 >