Seite 1 von 1

Kann mir jemand diese Code-Schreibweise erklären?

Verfasst: Dienstag 29. März 2016, 15:55
von Noranora
Hallo!

Ich bin auf folgenden Code gestoßen.

Code: Alles auswählen

#function to calculate number of words in each category within a sentence
sentimentScore <- function(sentences, vNegTerms, negTerms, posTerms, vPosTerms){
  final_scores <- matrix('', 0, 5)
  scores <- laply(sentences, function(sentence, vNegTerms, negTerms, posTerms, vPosTerms){
    initial_sentence <- sentence
    #remove unnecessary characters and split up by word 
    sentence <- gsub('[[:punct:]]', '', sentence)
    sentence <- gsub('[[:cntrl:]]', '', sentence)
    sentence <- gsub('\\d+', '', sentence)
    sentence <- tolower(sentence)
    wordList <- str_split(sentence, '\\s+')
    words <- unlist(wordList)
    #build vector with matches between sentence and each category
    vPosMatches <- match(words, vPosTerms)
    posMatches <- match(words, posTerms)
    vNegMatches <- match(words, vNegTerms)
    negMatches <- match(words, negTerms)
    #sum up number of words in each category
    vPosMatches <- sum(!is.na(vPosMatches))
    posMatches <- sum(!is.na(posMatches))
    vNegMatches <- sum(!is.na(vNegMatches))
    negMatches <- sum(!is.na(negMatches))
    score <- c(vNegMatches, negMatches, posMatches, vPosMatches)
    #add row to scores table
    newrow <- c(initial_sentence, score)
    final_scores <- rbind(final_scores, newrow)
    return(final_scores)
  }, vNegTerms, negTerms, posTerms, vPosTerms)
  return(scores)
 }    
 
#build tables of positive and negative sentences with scores
posResult <- as.data.frame(sentimentScore(posText, vNegTerms, negTerms, posTerms, vPosTerms))
negResult <- as.data.frame(sentimentScore(negText, vNegTerms, negTerms, posTerms, vPosTerms))
posResult <- cbind(posResult, 'positive')
colnames(posResult) <- c('sentence', 'vNeg', 'neg', 'pos', 'vPos', 'sentiment')
negResult <- cbind(negResult, 'negative')
colnames(negResult) <- c('sentence', 'vNeg', 'neg', 'pos', 'vPos', 'sentiment')    
 
#combine the positive and negative tables
results <- rbind(posResult, negResult)
leider sieht dieser mit den Pfeilen und anderen Extras ein bisschen anders aus, als ich das normal kenne: Also ist das doch eine andere Pythonversion!?....Kann mir jemand erklären, wie ich das in mein Ipython notebook bekomme?

Danke schon mal!

Re: Kann mir jemand diese Code-Schreibweise erklären?

Verfasst: Dienstag 29. März 2016, 15:58
von nezzcarth
Der Code ist in R geschrieben, nicht in Python. Wenn du den verwenden möchtest, musst dir halt R installieren. Theoretisch könnte man auch versuchen, den Code nach Python zu übersetzen (ggf. mit Hilfe von Pandas).