import torch
import transformers
# Load the pre-trained transformer model
model = transformers.BertForSequenceClassification.from_pretrained('bert-base-uncased')
# Define a function to extract subject-verb-object triples
def extract_svos(text):
# Tokenize the text
tokens = tokenizer.encode(text, return_tensors='pt')
# Prepare the input for the transformer model
input_ids = tokens['input_ids']
attention_mask = tokens['attention_mask']
# Run the input through the transformer model
outputs = model(input_ids, attention_mask)
# Extract the subject, verb, and object from the output
subject = torch.argmax(outputs.logits, dim=1)
verb = torch.argmax(outputs.logits, dim=1)
object = torch.argmax(outputs.logits, dim=1)
# Return the subject-verb-object triple
return subject, verb, object
# Test the function on some sample text
text = "John Smith is the CEO of XYZ Corporation."
subject, verb, object = extract_svos(text)
print(f"Subject: {subject}, Verb: {verb}, Object: {object}")
This code uses the popular BERT transformer model to extract subject-verb-object triples from text. It first tokenizes the text using the Hugging Face tokenizer, then prepares the input for the transformer model by converting the tokens to input IDs and creating an attention mask. The input is then run through the transformer model, and the output is used to extract the subject, verb, and object. Finally, the function returns the subject-verb-object triple.