簡體   English   中英

如何獲得以下 function 中每個元素的結果

[英]How do I get the result of every element in the following function

我有一個 function 以元組列表的形式返回每個單詞的詞性。 當我執行它時,我只得到第一個元素(第一個元組)的結果。 我想獲得該列表中每個元素(元組)的結果。 例如:

get_word_pos("I am watching")

我得到這個結果:

[('I', 'PRP'), ('am', 'VBP'), ('watching', 'VBG')]
'n'

但我想要的結果如下

"n"
"v"
"v"

我寫的 function 包含多個返回語句,這就是我只得到第一個元素為 output 的原因。 請如果有人可以修改我的 function 以便我得到所需的 output。 代碼如下:

training = state_union.raw("2005-GWBush.txt")
tokenizer = nltk.tokenize.punkt.PunktSentenceTokenizer(training)

def get_word_pos(word):
    
    sample = word
    
    tokenized = tokenizer.tokenize(sample)
    
    
    for i in tokenized:
        words = nltk.word_tokenize(i)
        tagged = nltk.pos_tag(words)
        print(tagged)
        
    for letter in tagged:
    #print(letter[1])
        if letter[1].startswith('J'):
            return wordnet.ADJ
        elif letter[1].startswith('V'):
            return wordnet.VERB
        elif letter[1].startswith('N'):
            return wordnet.NOUN
        elif letter[1].startswith('R'):
            return wordnet.ADV
        else:
            return wordnet.NOUN
        
    ```

當您迭代標記時,您會返回第一項的值。 你需要積累它們。 將它們附加到列表中是一種方法。 例如:

from nltk import word_tokenize, pos_tag
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer
from nltk.corpus import wordnet

training = state_union.raw('2005-GWBush.txt')
tokenizer = PunktSentenceTokenizer(training)

def get_word_pos(word):
    result = []
    for token in tokenizer.tokenize(word):
        words = word_tokenize(token)
        for t in pos_tag(words):
            match t[1][0]:
                case 'J':
                    result.append(wordnet.ADJ)
                case 'V':
                    result.append(wordnet.VERB)
                case 'R':
                    result.append(wordnet.ADV)
                case _:
                    result.append(wordnet.NOUN)
    return result


print(get_word_pos('I am watching'))

Output:

['n', 'v', 'v']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM