You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置spaCY检测PRP、MD、NN词性并输出指定提示文本?

How to Modify spaCy Code to Detect Specific POS Tags and Output a Custom Message

Hey there! Let's tweak your existing spaCy code to check for the presence of PRP, MD, and NN tags, and output your required message when all three are found. Here's a straightforward way to do it:

The Approach

  • First, we'll collect all unique part-of-speech tags from the input sentence using a set (sets automatically handle duplicates, so we don't waste time tracking repeated tags).
  • Next, we'll verify if all three target tags (PRP, MD, NN) exist in that collected set.
  • If they do, we'll print your custom prompt; we can also add an optional message for cases where some tags are missing.

Modified Code

import spacy

# Load the English language model once (best practice to load before user input)
nlp = spacy.load('en')

# Get input from the user
sent = input("insert sentence: \n\n")

# Process the sentence with spaCy
doc = nlp(sent)

# Initialize a set to store unique POS tags present in the sentence
present_tags = set()

# Iterate through tokens to collect tags and keep your original print output
for token in doc:
    print(token.text, token.tag_, token.dep_)
    present_tags.add(token.tag_)

# Define the tags we need to check for
required_tags = {'PRP', 'MD', 'NN'}

# Check if all required tags are present
if required_tags.issubset(present_tags):
    print("\n该句子中包含PRP、MD和NN")
else:
    # Optional: Print which tags are missing (remove this block if you don't need it)
    missing_tags = required_tags - present_tags
    print(f"\nMissing tags: {', '.join(missing_tags)}")

Key Details

  • present_tags = set(): Using a set ensures we only track each tag once, even if it appears multiple times in the sentence (like multiple nouns).
  • required_tags.issubset(present_tags): This cleanly checks if every tag in our required list exists in the collected tags—no messy multiple if statements needed.
  • We kept your original print(token.text, token.tag_, token.dep_) line so you can still see the full token breakdown alongside the tag check result.

Test Example

Input sentence: "I will bake a cake"
Output:
I PRP nsubj
will MD aux
bake VB ROOT
a DT det
cake NN dobj

该句子中包含PRP、MD和NN

内容的提问来源于stack exchange,提问作者John_appleseed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:41:50