In the Python programming language, first read from a CSV file containing three columns:
ID
title
content
then read a list of sentences from the 'content' column, and use the small Chinese model in the SpaCy toolkit to process that list, and return the following:
Tokenized sentences
POS tags of each token
dependency trees
NER
Vectors
Display the results as a dataframe using the display() function, and perform PCA on the average vector for each sentence. Use the first two dimensions as axes of a scatter plot.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a Python script that accomplishes the tasks you've outlined. This script assumes you have the necessary libraries installed, including pandas for data manipulation, spacy for natural language processing (specifically, the small Chinese model), matplotlib and sklearn for PCA and plotting. If you haven't installed these, you can do so by running pip install pandas spacy matplotlib scikit-learn. Additionally, you'll need to download the small Chinese SpaCy model using python -m spacy download zh_core_web_sm.
python
import pandas as pd
import spacy
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
# Load the Chinese SpaCy model
nlp = spacy.load("zh_core_web_sm")
# Function to process content and return results
def process_content(content):
doc = nlp(content)
# Initialize lists to hold results
tokenized_sentences = []
pos_tags = []
dependency_trees = []
ner_results = []
vectors = []
# Process the document (assuming one sentence per document for this example)
for sent in doc.sents:
tokenized_sentence = [token.text for token in sent]
tokenized_sentences.append(tokenized_sentence)
# POS Tags
pos_tag_list = [(token.text, token.pos_) for token in sent]
pos_tags.append(pos_tag_list)
# Dependency Trees
dependency_tree_list = [(token.text, token.dep_, token.head.text, token.head.pos_) for token in sent]
dependency_trees.append(dependency_tree_list)
# NER
ner_list = [(ent.text, ent.label_) for ent in doc.ents]
ner_results.append(ner_list)
# Vectors (average vector for the sentence)
sentence_vector = sent.vector
vectors.append(sentence_vector)
# Create a DataFrame to display results
results_df = pd.DataFrame({
'Tokenized Sentences': tokenized_sentences,
'POS Tags': pos_tags,
'Dependency Trees': dependency_trees,
'NER': ner_results,
'Vectors': vectors
})
return results_df, vectors
# Read from CSV file
def read_csv_and_process(file_path):
try:
csv_data = pd.read_csv(file_path)
except FileNotFoundError:
print(f"Error: The file {file_path} was not found.")
return
except pd.errors.EmptyDataError:
print(f"Error: The file {file_path} is empty.")
return
except pd.errors.ParserError:
print(f"Error: An error occurred while parsing {file_path}.")
return
# Ensure required columns exist
required_columns = ['ID', 'title', 'content']
if not all(col in csv_data.columns for col in required_columns):
print("Error: The CSV file must contain 'ID', 'title', and 'content' columns.")
return
content_list = csv_data['content'].tolist() # Assuming 'content' is the column of interest
all_results = []
all_vectors = []
for content in content_list:
if not isinstance(content, str) or not content.strip():
print("Skipping empty or malformed content.")
continue
results_df, vectors = process_content(content)
all_results.append(results_df)
all_vectors.extend(vectors)
# Display each result (for each sentence/content)
print(results_df.to_string())
print("----- Next Content's Results -----")
# Perform PCA on the average vectors for all sentences
if all_vectors:
pca = PCA(n_components=2)
principal_components = pca.fit_transform(all_vectors)
# Plot the results
plt.scatter(principal_components[:, 0], principal_components[:, 1])
plt.title('PCA of Sentence Vectors')
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.show()
else:
print("No valid sentence vectors to perform PCA.")
# Specify your CSV file path here
file_path = 'your_file.csv'
read_csv_and_process(file_path)
Important Notes:
SpaCy Model: Ensure you've downloaded the zh_core_web_sm model using python -m spacy download zh_core_web_sm.
CSV File Path: Replace 'your_file.csv' with the actual path to your CSV file.
Content Column: This script assumes sentences are in a column named 'content'. If your column is named differently, adjust the content_list = csv_data['content'].tolist() line accordingly.
Display Function: The display() function is typically used in Jupyter notebooks. If running this script outside of a notebook, you might need to adjust how results are displayed or saved. This version uses print(results_df.to_string()) for compatibility.
PCA and Plotting: This script performs PCA on the average sentence vectors and plots the first two principal components. The interpretation of these components depends on the context of your project.