lemmatize toàn bộ cột bằng hàm lambda
Sep 09 2020
Tôi đã kiểm tra mã này cho một câu và tôi muốn chuyển đổi mã này để tôi có thể bổ sung toàn bộ cột trong đó mỗi hàng bao gồm các từ không có dấu câu như: deportivas calcetin hombres deportivas shoes
import wordnet, nltk
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
import pandas as pd
df = pd.read_excel(r'C:\Test2\test.xlsx')
# Init the Wordnet Lemmatizer
lemmatizer = WordNetLemmatizer()
sentence = 'FINAL_KEYWORDS'
def get_wordnet_pos(word):
"""Map POS tag to first character lemmatize() accepts"""
tag = nltk.pos_tag([word])[0][1][0].upper()
tag_dict = {"J": wordnet.ADJ,
"N": wordnet.NOUN,
"V": wordnet.VERB,
"R": wordnet.ADV}
return tag_dict.get(tag, wordnet.NOUN)
#Lemmatize a Sentence with the appropriate POS tag
sentence = "The striped bats are hanging on their feet for best"
print([lemmatizer.lemmatize(w, get_wordnet_pos(w)) for w in nltk.word_tokenize(sentence)])
Giả sử Tên cột là df ['keywords'], bạn có thể giúp tôi sử dụng hàm lambda để bổ sung toàn bộ cột như tôi bổ sung câu trên được không?
Rất cám ơn trước
Trả lời
AvivYaniv Sep 09 2020 at 16:41
Của bạn đây:
- Dùng
applyđể áp dụng cho các câu của cột - Sử dụng biểu thức lambda lấy giá trị
sentenceđầu vào và áp dụng hàm bạn đã viết, tương tự như cách bạn sử dụng trong câu lệnh print
Như các từ khóa được bổ sung:
# Lemmatize a Sentence with the appropriate POS tag
df['keywords'] = df['keywords'].apply(lambda sentence: [lemmatizer.lemmatize(w, get_wordnet_pos(w)) for w in nltk.word_tokenize(sentence)])
Dưới dạng một câu bổ ngữ ( jointừ khóa sử dụng ''):
# Lemmatize a Sentence with the appropriate POS tag
df['keywords'] = df['keywords'].apply(lambda sentence: ' '.join([lemmatizer.lemmatize(w, get_wordnet_pos(w)) for w in nltk.word_tokenize(sentence)]))