简体   繁体   中英

How to Search and Counting Whether the Set of Elements in List

Below is the code that I search and count the pos_xist named list that holds the crawled element of en.wiktionary.org. The list holds the possible Part of Speech tag (with something not pos too) of wiktionary, and I search that list only to count how many of them in the list. How can I shorten this code below in a more concise way?

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

You could create a list of words to search for, and iterate over each item in pos_xist with aa generator expression:

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

If you want to limit to the first ten items use slicing pos_xist[:10] .

No exception handling should be necessary.

postaglist=['Noun','Verb'...]
for item in pos_xist:
    if item in postaglist:
        count=count+1

form a list of all possible pos tags and search in them.

You could use the any builtin coupled with just going through the list per item rather than waiting until an error is thrown.

It would look something like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM