%scala import org.apache.spark.sql.{DataFrame, SparkSession} import…
- User
%scala
import org.apache.spark.sql.{DataFrame, SparkSession} import org.apache.spark.sql.functions. import scala.collection.mutable
class CategoriaKeyword(spark: SparkSession, categoriesDF: DataFrame, textDF: DataFrame, categoryCol: String = “Categoria”, keywordsCol: String = “Palavras-Chave”, textCol: String = “Texto”) {
// Convert categories and keywords into a Map for quick lookup private val keywordToCategory = mutable.MapString, String
categoriesDF.collect().foreach { row => val category = row.getAsString val keywordsString = row.getAsString if (keywordsString != null) { keywordsString.split(", ").foreach { keyword => keywordToCategory.put(keyword.trim.toLowerCase, category) } } }
def buscarPalavrasChave(): DataFrame = { import spark.implicits.
val resultados = textDF.map { row => val texto = row.getAsString.toLowerCase // Count occurrences of each keyword in the text val wordCount = texto.split(“\s+”).groupBy(identity).mapValues(.length) val categoryScores = mutable.MapString, Int keywordToCategory.keys.foreach { keyword => val keywordCount = wordCount.getOrElse(keyword, 0) if (keywordCount > 0) { val categoria = keywordToCategory(keyword) categoryScores(categoria) = categoryScores.getOrElse(categoria, 0) + keywordCount } } // Determine the highest scoring category val categoriaMaisProvavel = categoryScores.maxByOption(.2).map(._1).getOrElse(“Nenhuma categoria encontrada”) // Find unique keywords present in the text val palavrasLocalizadas = keywordToCategory.keys.filter(texto.contains).toSet // Create the result row (row.getAsString, categoriaMaisProvavel, palavrasLocalizadas.toList, palavrasLocalizadas.size) }.toDF(“Texto”, “Categoria Encontrada”, “Palavras Localizadas”, “Contador Palavras Localizadas”) resultados} }
// Example usage assuming SparkSession is already created as spark:
// Categories DataFrame val categoriesDF = Seq( (“Cartões - Anuidade - Negociação”, “anuidade, negociação”), // … add all the categories ).toDF(“Categoria”, “Palavras-Chave”)
// Text DataFrame - placeholder data to match your example val textDF = Seq( (“Estou com problemas com a fatura e a segunda via do cartão.”), // … other example texts ).toDF(“Texto”)
// Initialize and run the keyword search val categorizador = new CategoriaKeyword(spark, categoriesDF, textDF) val resultDF = categorizador.buscarPalavrasChave()
// Display the result resultDF.show(false)(console):4:1 expected (
this| Id) import scala.collection.mutable ^ (console):4:1 expected (this| Id) - Assistant
- User
(console):3:1 expected (
this| Id) import scala.collection.mutable ^ (console):3:1 expected (this| Id) - Assistant
- User
nao use classe
- Assistant
- User
nao use classe nem def função
- Assistant
- User
%scala // Create a keyword-to-category map val keywordToCategory = mutable.MapString, String categoriesDF.collect().foreach { row => val category = row.getAsString val keywordsString = row.getAsString if (keywordsString != null) { keywordsString.split(“,”).foreach { keyword => keywordToCategory.put(keyword.trim.toLowerCase, category) } } }(console):2:42 expected ("}" | end-of-input) (console):2:42 expected ("}" | end-of-input) val keywordToCategory = mutable.MapString, String
- Assistant
The error you're encountering is due to incorrect syntax when declaring and initializing a mutable map. When creating a map in Scala, you should use the proper type constructors and pay attention to the symbols used for quoting strings and defining types. Let's correct this block of code:
// Import necessary packages import scala.collection.mutable // Create a keyword-to-category map with the correct syntax val keywordToCategory = mutable.Map[String, String]() // Example categories DataFrame (assuming categoriesDF is already defined in your environment) categoriesDF.collect().foreach { row => val category = row.getAs[String]("Categoria") // Ensure you use the correct column name val keywordsString = row.getAs[String]("Palavras-Chave") // Ensure you use the correct column name if (keywordsString != null) { keywordsString.split(",").foreach { keyword => keywordToCategory.put(keyword.trim.toLowerCase, category) } } } // Now the keywordToCategory map is correctly filled with data - User
%scala import spark.sql
val df = spark.sql("SELECT * FROM prd.s_stbr_dcr_dcr_stt.stt_trsc")
val dfFiltrada = df.filter(df("ma_liga") === "202408" && (df("tx_trsc_segm").like("%cartao%") || df("tx_trsc_segm").like("%cartões%")))
val result = dfFiltrada.head
println(result) ao final gostaria de um dataframe pandas
- Assistant
To accomplish your task of filtering a DataFrame in Apache Spark and converting the final result to a pandas DataFrame, we will follow these steps:
- Retrieve data from the SQL source.
- Filter the DataFrame based on your conditions.
- Convert the result to a pandas DataFrame.
Let's walk through the code with an explanation:
- User
cmd15.sc:18: value toDF is not a member of Seq[org.apache.spark.sql.Row] val res15_5 = result.toSeq.toDF() ^Compilation Failed
- Assistant