📌  相关文章
📜  Python程序来检查一个词是否是名词

📅  最后修改于: 2022-05-13 01:54:52.001000             🧑  作者: Mango

Python程序来检查一个词是否是名词

给定一个单词,任务是使用Python编写一个Python程序来查找该单词是否是名词。

例子:

Input: India
Output: India is noun.

Input: Writing
Output: Writing is not a noun.

有各种库可以用来解决这个问题。

方法 1 :使用 NLTK 的 PoS 标记

Python3
# import required modules
import nltk
nltk.download('averaged_perceptron_tagger')
  
# taking input text as India
text = "India"
ans = nltk.pos_tag()
  
# ans returns a list of tuple
val = ans[0][1]
  
# checking if it is a noun or not
if(val == 'NN' or val == 'NNS' or val == 'NNPS' or val == 'NNP'):
    print(text, " is a noun.")
else:
    print(text, " is not a noun.")


Python3
# import required modules
import spacy
nlp = spacy.load("en_core_web_sm")
  
# taking input
text = "Writing"
  
# returns a document of object
doc = nlp(text)
  
# checking if it is a noun or not
if(doc[0].tag_ == 'NNP'):
    print(text, " is a noun.")
else:
    print(text, " is not a noun.")


输出:

India is a noun.

方法 2:使用 Spacy 进行 PoS 标记

蟒蛇3

# import required modules
import spacy
nlp = spacy.load("en_core_web_sm")
  
# taking input
text = "Writing"
  
# returns a document of object
doc = nlp(text)
  
# checking if it is a noun or not
if(doc[0].tag_ == 'NNP'):
    print(text, " is a noun.")
else:
    print(text, " is not a noun.")

输出:

Writing is not a noun.