October 26, 2026
Clustering of poems in Portuguese Language based on quantitative variables
Raquel Akemi Okuno Kitazume da Silva; Daniel Alvarez Firmino
DOI: 10.22167/2675-6528-202603391
Article derived from a Course Conclusion Work (TCC), with content based on the student’s original work and adapted to the editorial format of the E&S Magazine with the support of the ResumeAI tool, an artificial intelligence solution developed by Instituto Pecege for textual synthesis and organization.
Summary
The curation of poems by textual complexity for educational purposes aids the pedagogical planning of parents and educators. With the objective of optimizing text selection for the teaching environment, an automated approach was proposed for the grouping of poems in Portuguese, based on levels of structural similarity. The methodology employed the K-means Clustering Method. Initially, a corpus of 2,834 works was collected from a digital repository of poems through data scraping. After preprocessing, which included text treatment by Regular Expressions and Natural Language Processing, nine quantitative variables were extracted to characterize the textual dimension, morphology, lexical richness, linguistic rarity, and conceptual density of the poems. Subsequently, the K-means algorithm was applied, which organized the poems into three distinct and cohesive groups, validated with the aid of Principal Component Analysis for visualization and interpretation. Group 0 brought together short poems with sophisticated vocabulary and high lexical density; Group 1, texts of intermediate length and simpler vocabulary; and Group 2, long poems with greater word repetition. The results demonstrated the ability to systematically segment the difficulty level of the works, offering valuable support for educational practice. This approach equips teachers and parents in the strategic curation of reading, aligned with the cognitive and linguistic development of students.
Keywords: Poem analysis; Education; Natural Language Processing; Web scraping.
1. Introduction
The poem is a complex textual genre, which explores and expands the limits of language to compose images and meanings (Araujo Junior, 2021). Its definition encompasses a formal composition that follows grammatical, semantic, and poetic restrictions, where the latter refers to elements such as style, meter, rhyme, and cadence (Marmik Pandya, 2016). Throughout history, poems have been the object of study of Poetry Theory, which seeks to analyze and synthesize the aesthetic and structural criteria of literary works.
The use of poems in the education of children and adolescents offers significant benefits for the formation of experienced readers (Morais, 2018). Reading aloud and memorizing poems activate brain regions associated with reading, promoting the plasticity of the neural system and engaging long-term and short-term memory (Morais & de Melo, 2018). However, selecting poems appropriate to the age and cognitive development of students is a challenge. Poems for younger children, for example, should feature abundant rhymes, appropriate length, and universal themes, while texts for older students can be more extensive, complex, and with profound themes.
In this scenario, the curation of poems by textual complexity is essential to assist the pedagogical planning of parents and educators. The absence of tools that automatically segment poems by difficulty levels represents a practical gap, making the manual process time-consuming and subjective. Automatic segmentation, based on textual complexity, emerges as a valuable tool to support teachers and parents in the strategic selection of teaching materials.
Natural Language Processing (NLP) has advanced significantly in the automatic analysis of poems. Pioneering works in the English language, such as Logan (1988), explored metric complexity. Subsequently, Hayward (1991, 1996) used neural networks for metric structures, and Plamondon (2006) developed algorithms to identify meter and rhymes. In Portuguese, Araujo and Mamede (2002) analyzed line length, rhyme, and stanza structure, with Mamede et al. (2004) improving word suggestion. The Aoidos system (Mittmann et al., 2018) also contributed to metric annotation and rhyme detection.
Despite these advances, the application of clustering methods based on quantitative variables to optimize the educational curation of poems in Portuguese still lacks systematic exploration. Therefore, the need for an approach that organizes these texts in a structured and interpretable way is justified. The objective of this work is to apply the K-means Clustering Method to a corpus of poems to define well-defined groups, aiming to optimize the curation of texts for the educational environment.
2. Material and Methods
This study adopted a quantitative and computational approach for the clustering of poems in Portuguese Language, aiming to optimize the curation of texts for the educational environment. The methodology employed a Data Science pipeline, which included the automated collection of a corpus, its preprocessing, the extraction of linguistic and structural variables, dimensionality reduction, and the application of unsupervised machine learning techniques for clustering.
Data collection was performed by “web scraping” on the Escritas.org portal, using Python (McKinney, 2018) with BeautifulSoup4 for static HTML syntactic analysis. For tracking and automating navigation in dynamic elements via JavaScript, the Selenium Framework (Babu, 2020) was employed. The algorithm extracted metadata such as author, nationality, title, and poem body, resulting in an initial set of 2,890 observations.
After collection, the raw data underwent cleaning and standardization. Regular Expressions (Regex) were applied for content processing, removing duplicate records, null fields, and inconsistencies in extraction, such as incomplete text body captures. Manual inspection was performed to ensure the integrity of the poetic structure and the preservation of verse arrangement. After this filtering, the final database was consolidated with 2,834 records.
From the cleaned corpus, nine quantitative variables were extracted, categorized into text dimension, morphology, lexical richness, linguistic rarity, and conceptual density. For the text dimension, three variables were obtained: `qtd_estrofes` (number of stanzas), `qtd_versos` (number of verses), and `num_tokens` (total number of words in the poem, including repetitions). Tokenization of the text body, segmenting the content into minimal units, was performed via Regex.
In the morphology category, two variables were extracted based on character length. The `max_word_len` variable expresses the number of characters in the longest word in each poem. The `avg_word_len` was calculated by the ratio between the total number of characters in the text and its total number of tokens, serving as an indicator of linguistic density.
For lexical richness, two variables were obtained. `ttr_clean` (Type-Token Ratio) represents the ratio between unique words (types) and the total number of words (num_token), indicating vocabulary variation. `hapax_rate_clean` (Hapax Legomena rate) corresponds to the proportion of words that occur only once in the text, measuring vocabulary exclusivity.
Linguistic rarity was measured by the `rarity_rate` variable, calculated based on an inventory of the thousand most recurrent Portuguese words, obtained from linguistic study repositories. For conceptual density, lemmatization was applied to the tokens, using the `pt_core_news_sm` model from the SpaCy library and the NLTK library in Python (Caseli & Nunes, 2023). From this, `ttr_lemma` (Type-Token Ratio of lemmas) was calculated, which aims to measure concept diversity.
Dimensionality reduction was performed using Principal Component Analysis (PCA), according to Johnson and Wichern (1998). This procedure aimed to reduce the data volume with minimal information loss, standardizing the data by the Z-score method before calculating the correlation matrix. For defining the ideal number of components, the accumulated explained variance was evaluated, seeking to represent at least 70% of the total variability of the original data (Hair et al., 2018).
For the clustering of poems, the K-means Clustering Method, proposed by MacQueen (1967), was employed. This algorithm allocates each observation to the cluster whose centroid, defined by the arithmetic mean of the group, presents the shortest distance in relation to the observation. The iterative process involved the initial division of observations into k groups, the linking of each observation to the nearest centroid, and the recalculation of centroids until group stability.
The determination of the ideal number of clusters for the K-means algorithm was performed using the Elbow Method, which is based on the calculation of the Within-Cluster Sum of Squares (WCSS). The inflection point of the resulting curve, where the decrease in value becomes less pronounced, indicated the number of clusters. Principal Component Analysis was used exclusively for visualization and interpretation of the formed clusters, and not as input for the clustering method.
3. Results and Discussion
The results obtained in this study detail and discuss the segmentation of a corpus of poems in the Portuguese Language, carried out through the K-means Clustering Method. The initial analysis focused on the relationship between the extracted textual metrics, providing the basis for choosing the number of clusters and the subsequent interpretation of the formed groups. The visualization and understanding of these clusters were enhanced by the application of Principal Component Analysis, which allowed for a clear representation of the distinctive characteristics of each category of poems.
The research demonstrated the ability to systematically segment the difficulty level of works, offering valuable support for educational practice. This approach equips teachers and parents in the strategic curation of reading, aligned with students’ cognitive and linguistic development, by providing an objective tool for text selection. The findings confirm the feasibility of using Natural Language Processing techniques and unsupervised machine learning to optimize the selection of didactic materials, a central objective of this work.
Correlation Analysis of Variables
The correlation analysis between the nine extracted variables revealed significant association patterns. Variables related to the textual dimension, such as the number of stanzas, the number of verses, and the total number of words (num_tokens), showed a strong positive correlation among themselves, with Pearson coefficients close to one. For example, the correlation between the number of stanzas and the number of verses was 0.68, while the correlation between the number of verses and the total number of words was 0.84. This high association is expected, as these metrics reflect the physical volume of the texts, indicating a natural redundancy in the information they carry.
Similarly, lexical richness indicators, including the Type-Token Ratio (ttr_clean), the Hapax Legomena Rate (hapax_rate_clean), and the Lemmatized Type-Token Ratio (ttr_lemma), also exhibited a strong positive association. The ratio of unique words to total words (ttr_clean) strongly correlated with the proportion of words occurring only once (hapax_rate_clean), with a coefficient of 0.83, and with the variety of concepts and themes addressed (ttr_lemma), with a coefficient of 0.71. The linguistic rarity rate (rarity_rate) also showed a strong positive correlation with ttr_lemma, reaching 0.94. These correlations indicate that these metrics capture similar aspects of vocabulary diversity and sophistication.
In contrast, lower correlations were observed between some variables, suggesting that they provide distinct and complementary information to the model. For example, the average word length (avg_word_len) showed more modest correlations with textual dimension and lexical richness variables. The ttr_clean, in turn, showed a negative correlation with the number of stanzas (-0.24), verses (-0.28), and number of tokens (-0.28), indicating that longer poems tend to have lower relative lexical diversity due to repetition. These differences in the associations between metrics highlight the multifaceted complexity of poetic language and the need for a diverse set of variables for its analysis.
Principal Component Analysis
After evaluating the correlations, the data were normalized using the Z-score method, an essential step to ensure that variables with different scales could be compared equitably, preventing metrics with larger absolute values from dominating the analysis. Subsequently, to determine the optimal number of clusters for the clustering algorithm, the Elbow Method was applied. The analysis of the within-cluster sum of squares (WCSS) indicated a sharper drop between one and three clusters, suggesting that three clusters would be the most suitable configuration for the study’s objectives.
The choice of three groups was justified by the search for pedagogical interpretability that would result in categories of poems that were simultaneously distinct and applicable to the educational context. With this definition, the K-means Clustering Method was applied, resulting in the formation of three distinct groups. Group 0 encompassed 1,538 observations, corresponding to 54.27% of the total corpus. Group 1 included 1,205 poems, representing 42.52% of the total, and Group 2, the smallest, with 91 observations, or 3.21% of the corpus.
To aid in the visualization and interpretation of the formed groups, Principal Component Analysis (PCA) was used, which reduced the dimensionality of the data. It is important to emphasize that PCA was employed exclusively for visualization and interpretation purposes, and not as input for the K-means clustering method. To ensure an adequate representation of the data’s variance, three principal components were retained, which together explained 76.33% of the total variability. Principal Component 1 (PC1) retained 36.90% of the variance, Principal Component 2 (PC2) explained 27.49%, and Principal Component 3 (PC3) contributed 11.95%.
The principal component analysis revealed their relationships with the original variables. Principal Component 1 (PC1) showed a strong negative relationship with lexical richness and conceptual density variables, such as ttr_clean (-0.80), hapax_rate_clean (-0.86), and ttr_lemma (-0.85). In contrast, PC1 showed a positive relationship with textual dimension variables, including the number of stanzas (0.53), the number of verses (0.61), and the total number of words (0.62). This means that high PC1 values indicate longer poems with lower lexical and conceptual diversity, while low values suggest the opposite.
Principal Component 2 (PC2) demonstrated a positive relationship with most variables, with the exception of ttr_clean, which showed a weaker correlation (0.18). Variables such as the number of stanzas (0.56), the number of verses (0.66), the total number of words (0.63), the maximum word length (0.60), and the average word length (0.63) had higher positive correlations with PC2. This component can be interpreted as a general indicator of the poem’s extent and complexity, being directly proportional to all dimensions except relative lexical diversity.
Finally, Principal Component 3 (PC3) exhibited a strong negative relationship with morphology variables, specifically maximum word length (-0.56) and average word length (-0.50). This implies that lower values for PC3 are associated with poems with longer words and, consequently, a more sophisticated vocabulary. PC3 also showed positive relationships with ttr_clean (0.35), hapax_rate_clean (0.25), and ttr_lemma (0.18). In summary, PC1 contrasts the textual dimension with lexical richness, PC2 is directly proportional to all poem dimensions, and PC3 is an indicator of word length, with lower values associated with longer words.
Interpretation of the groups
The joint analysis of principal components allowed for the tracing of distinctive profiles for each group of poems. Group 0, visually represented with low values for PC1 and values concentrated near zero for PC2 and PC3, varying between positive and negative, consolidated itself as the grouping of short poems, but with high lexical density and richness. This group is characterized by diverse and dense language, with a high rate of rare words and low repetition of words and concepts, reflecting traditional lyricism and fixed forms such as the sonnet.
In contrast, Group 2, which positioned itself with positive values for PC1, PC2, and PC3, ranging between negative and positive but with a positive predominance, gathered poems of greater structural extent, with more verses and stanzas. This group demonstrated that, the larger the poem, the greater the chances of word repetition, although the vocabulary tends to be morphologically simpler. Group 1, in turn, presented positive values for PC1 and values ranging between negative and positive, concentrated around zero for PC2 and PC3. This intermediate group has a larger structure than Group 0, but significantly smaller than Group 2, and is characterized by a simpler and more colloquial vocabulary.
The detailed analysis of the variables through boxplot graphs reinforced these distinctions. For textual dimension variables, such as number of stanzas, verses, and number of tokens, Group 2 exhibited the highest medians, indicating that it is composed of considerably longer texts. Group 1 followed with texts of intermediate length, and Group 0 presented the lowest medians, characterized by conciseness. This clear separation demonstrates the effectiveness of the clustering method in differentiating poems based on their physical length.
Regarding morphology, the variables maximum word length (max_word_len) and average word length (avg_word_len) showed more homogeneous distributions. However, Group 0 stood out with the highest median for average word length, indicating that, despite being shorter, their poems employ more sophisticated words. Group 2, in turn, presented the highest median for maximum word length. These observations suggest that lexical sophistication is not directly linked solely to poem length, but also to the choice of more elaborate terms.
For the lexical richness variables, ttr_clean and hapax_rate_clean, Group 0 obtained the highest median values, with ttr_clean above 0.9, indicating minimal word repetition. Groups 1 and 2 presented similar distributions regarding lexical richness, however, Group 1 exhibited higher repetition rates and a lower number of unique words. Regarding linguistic rarity (rarity_rate), Group 0 again stood out with the highest median, followed by Group 2 and, lastly, Group 1. This suggests that, despite being more concise, Group 0’s poems use a more erudite or specific vocabulary, contributing to their greater complexity.
Conceptual density, measured by ttr_lemma, was also higher in Group 0, indicating a broader diversity of concepts and themes addressed. Groups 1 and 2, although distinct in dimension, showed themselves to be quite similar in this regard. Visualization through a radar chart, with data normalized by the Z-Score Method, corroborated these characteristics. Group 0 exhibited the highest averages for lexical density, rarity, and morphology, and the lowest for textual dimension. Group 1 presented shorter poems, with low values for length and lower lexical diversity. Group 2, in turn, contained the longest texts with greater word repetition.
The semantic analysis, performed through word clouds, revealed the most frequent words in each group. For Group 0, terms such as “life”, “love”, “where”, “so”, “eyes”, “everything”, “night”, “about”, “sun”, and “light” were predominant. In Group 1, the most common words included “love”, “life”, “everything”, “where”, “me”, “because”, “eyes”, “so”, “night”, and “nothing”. For Group 2, “life”, “everything”, “where”, “because”, “night”, “me”, “about”, “God”, “earth”, and “comes” stood out. The thematic homogeneity observed in the corpus suggests that the K-means segmentation was guided mainly by morphological and structural criteria, rather than by specific topics.
Examples of poems located in the centroids of each group illustrated these characteristics. The poem “De Tarde”, by Cesário Verde, belonging to Group 0, with four stanzas, 16 verses, and 96 words, exemplified conciseness and refined vocabulary, with terms like “aguarela” (watercolor), “imposturas” (impostures), and “granzoal” (granite quarry), reflecting a realistic and objective writing style. The poem “O menino azul”, by Cecília Meireles, from Group 1, with five stanzas, 24 verses, and 105 words, demonstrated a simple and puerile aesthetic, but with rhythmic sophistication. “Napoleão de Waterloo”, by Gonçalves de Magalhães, from Group 2, with 20 stanzas, 146 verses, and 935 words, displayed erudite language and a solemn and epic tone, with words like “eclipsou-se” (eclipsed) and “obumbrava” (overshadowed), confirming the characteristic of long and complex texts.
Key Authors
The distribution of the main authors in the corpus revealed interesting patterns in relation to the groups formed. In Group 0, Olavo Bilac stood out, with 80.6% of his poems classified in this category, and Florbela Espanca, with approximately 60.2% of her works. Both authors are known for their vast production of sonnets and poems with concise structure and elaborate language, such as “Uma tarde de Outono”, “Ora (direis) ouvir estrela!”, “Fanatismo” and “Amiga”. This concentration reinforces the characterization of Group 0 as containing works of high lexical sophistication and reduced structure.
For Group 1, Fernando Pessoa emerged as the most relevant author, with a significant portion of his poems. Other important authors in this group include Vinicius de Moraes and Cecília Meireles, whose creations are often intended for children, such as “O pato”, “A casa”, “Elefantinho”, “Ou isto ou aquilo”, and “O colar de Carolina”. These poems are characterized by a smaller structure and a simpler, more childlike language, aligning with Group 1’s profile of intermediate-length texts with more accessible vocabulary. Fernando Pessoa’s presence in different groups demonstrates the versatility of his work.
In Group 2, which brings together the longest poems with the greatest repetition of words, Castro Alves and, again, Fernando Pessoa stood out. The presence of Castro Alves is consistent with the nature of his poems, often extensive and epic, which fit the characteristics of greater textual dimension and vocabulary repetition observed in this group. The recurrence of Fernando Pessoa in more than one group underlines the diversity of his style and the breadth of his poetic production, which can range from simpler texts to works of great scope and complexity.
In summary, the application of the K-means Clustering Method, supported by Principal Component Analysis and various visualizations, allowed for the effective segmentation of a vast corpus of Portuguese-language poems into three distinct groups. These groups were characterized by clear differences in textual dimension, lexical richness, linguistic rarity, and conceptual density, offering a robust tool for curating poems in educational contexts. The results demonstrate that quantitative textual metrics are capable of organizing poetic works in a consistent and interpretable manner, facilitating the selection of didactic materials suitable for students’ cognitive and linguistic development.
4. Conclusion
This work aimed to apply the K-means Clustering Method to a corpus of poems in the Portuguese Language for the definition of well-defined groups, seeking to optimize the curation of texts for the educational environment. For this purpose, a corpus of 2,834 works was collected and pre-processed, and nine quantitative variables were extracted to characterize the textual dimension, morphology, lexical richness, linguistic rarity, and conceptual density of the poems. It was found that the K-means algorithm organized the poems into three distinct and cohesive groups, whose validation and interpretation were aided by Principal Component Analysis. Group 0 brought together short poems with sophisticated vocabulary and high lexical density, presenting the highest rate of rare words and lower repetition. Group 1 comprised texts of intermediate length and simpler, more colloquial vocabulary. Finally, Group 2 encompassed long poems, with a greater number of stanzas and verses, and greater word repetition, although with morphologically simpler vocabulary. The segmentation was guided mainly by morphological and structural criteria, rather than specific topics.
The developed approach offers a significant practical contribution by equipping teachers and parents with strategic reading curation, aligned with students’ cognitive and linguistic development. This objective tool aids in selecting appropriate didactic materials, filling a gap in the automatic segmentation of poems by difficulty levels. As a suggestion for future studies, we propose expanding the analysis and extraction of textual features, including counting poetic syllables, identifying rhymes, classifying by functional form (such as haiku, sonnets, free verse), and more in-depth semantic analysis. Additionally, we recommend developing a user interface that allows educators to intuitively filter the poem database by lexical and thematic complexity.
Bibliographic References
Araujo Junior, J. R. (2021). Mineração de poemas através de técnicas de processamento de linguagem natural . Campina Grande, Paraíba, Brasil.
Hayward, M. (1991). A connectionist model of poetic meter
Logan, H. M. (1988). Computer analysis of sound and meter in poetry. JSTOR, 19-24.
Morais, M. R.; de Melo, M. A. (2018). Neuropoética da aprendizagem estratégias metacognitivas de leitura de poesia para a formação de memórias. Em M. d. Alves, & N. S. Miranda, Ensino de Língua Portuguesa no Ensino Fundamental Volume II (pp. 104-124). Natal: UFRN.
Pandya, M. (2016). NLP based poetry analysis and generation. Disponível em: https://www.researchgate.net/publication/313874773. Acesso em: 15/10/2025
Article originating from the Final Course Project of the Specialization in Data Science and Analytics of the MBA USP/Esalq
To learn more about the course, click here and access the MBX Academy platform