Last active
November 14, 2023 17:00
-
-
Save lucianoschillagi/089b2955e835c0dfb6e6e57bbf9e447a to your computer and use it in GitHub Desktop.
Identifying parts of speech
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import SwiftUI | |
| import NaturalLanguage | |
| struct TaggedTextView: View { | |
| let text = "This is your life. Do what you love and do it often." | |
| let text2 = "― Holstee Manifesto, The Wedding Day (extract)" | |
| let textButton = "Tag the text" | |
| @State private var taggedText: [String] = [] | |
| @State private var taggedTextOn = false | |
| var body: some View { | |
| ZStack { | |
| Color.red.opacity(0.65).ignoresSafeArea() | |
| VStack(alignment: .leading) { | |
| if taggedTextOn { | |
| ForEach(taggedText, id: \.self) { | |
| Text($0).font(.system(size: 40)).bold().fontDesign(.rounded) | |
| } | |
| } else { | |
| Text(text).font(.system(size: 80)).bold().fontDesign(.rounded).padding(.bottom) | |
| Text(text2) | |
| .padding(.bottom) | |
| Button(textButton) { | |
| runTaggedText() | |
| }.buttonStyle(.borderedProminent) | |
| } | |
| } | |
| .padding(25) | |
| } | |
| } | |
| func runTaggedText() { | |
| taggedTextOn = true | |
| let tagger = NLTagger(tagSchemes: [.lexicalClass]) | |
| tagger.string = text | |
| let options: NLTagger.Options = [.omitPunctuation, .omitWhitespace] | |
| tagger.enumerateTags(in: text.startIndex..<text.endIndex, unit: .word, scheme: .lexicalClass, options: options) { tag, tokenRange in | |
| if let tag = tag { | |
| taggedText.append("\(text[tokenRange]): \(tag.rawValue)") | |
| } | |
| return true | |
| } | |
| } | |
| } | |
| #Preview { | |
| TaggedTextView() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment