File size: 1,864 Bytes
2b7f7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Varre as frases dos blogues com o NaturalLanguage da Apple (28 Nov 2026): os nomes de pessoa, de lugar e de
// organização que o NLTagger reconhece (nameType), e se a frase tem um verbo (lexicalClass), em português.
// Uso: varrer <entrada.tsv: id \t texto> <saída.tsv: id \t pessoas \t lugares \t organizações \t verbos>
import Foundation
import NaturalLanguage
let a = CommandLine.arguments
let linhas = try String(contentsOfFile: a[1], encoding: .utf8).split(separator: "\n").map(String.init)
var fora = ""
let tagger = NLTagger(tagSchemes: [.nameType, .lexicalClass])
for l in linhas {
    let p = l.split(separator: "\t", maxSplits: 1).map(String.init)
    guard p.count == 2 else { continue }
    let texto = p[1]
    tagger.string = texto
    tagger.setLanguage(.portuguese, range: texto.startIndex..<texto.endIndex)
    var pessoas: [String] = [], lugares: [String] = [], orgs: [String] = []
    let opts: NLTagger.Options = [.omitPunctuation, .omitWhitespace, .joinNames]
    tagger.enumerateTags(in: texto.startIndex..<texto.endIndex, unit: .word, scheme: .nameType, options: opts) { tag, r in
        switch tag {
        case .personalName?: pessoas.append(String(texto[r]))
        case .placeName?: lugares.append(String(texto[r]))
        case .organizationName?: orgs.append(String(texto[r]))
        default: break
        }
        return true
    }
    var verbos = 0
    tagger.enumerateTags(in: texto.startIndex..<texto.endIndex, unit: .word, scheme: .lexicalClass, options: [.omitPunctuation, .omitWhitespace]) { tag, _ in
        if tag == .verb { verbos += 1 }
        return true
    }
    fora += "\(p[0])\t\(pessoas.joined(separator: "|"))\t\(lugares.joined(separator: "|"))\t\(orgs.joined(separator: "|"))\t\(verbos)\n"
}
try fora.write(toFile: a[2], atomically: true, encoding: .utf8)
print("\(linhas.count) frases varridas")