Home > Blockchain >  kotlin: Reading a text file and storing content in lists
kotlin: Reading a text file and storing content in lists

Time:10-21

I have a text file that has fonts and its meta data

10 52

a 10
               
.oooo.  
`P  )88b 
.oP"888 
d8(  888 
`Y888""8o
        
        
        
b 11
.o8      
"888      
888oooo. 
d88' `88b
888   888
888   888
`Y8bod8P'
         
         
         
c 10
        
        
.ooooo. 
d88' `"Y8
888      
888   .o8
`Y8bod8P'

                           
                     
X 15
ooooooo  ooooo
`8888    d8' 
  Y888..8P   
   `8888'    
  .8PY888.   
 d8'  `888b  
o888o  o88888o
             
             
             
Y 14
oooooo   oooo
`888.   .8' 
 `888. .8'  
  `888.8'   
   `888'    
    888     
   o888o    
            
            
            
Z 14
oooooooooooo
d'""""""d888'
     .888P  
    d888'   
  .888P     
 d888'    .P
.8888888888P 

The letters are capitals and small. And I want to take them from the file and store each letter in a list. Therefore I can use it later on…

I tried using filters… but I couldn’t split the result into arrays/lists using chunked() or widowed() because letters are either 5 or 7 or more lines.

val romanFont = File("roman.txt").readLines().filter { it.length > 5 }

The file has 52 letters… Any idea?

CodePudding user response:

It looks like every letter has 7 rows. Which also makes sense for an asci font. Every font-letter starts by a line which starts with a letter followed by a space and a number. So we can recognize this pattern by a simple regex (^[a-zA-Z] [0-9]{1,2}). Now we use this knowledge to iterate over all lines and collect out Letter-List:

val font = """
    a 10
                   
    .oooo.  
    `P  )88b 
    .oP"888 
    d8(  888 
    `Y888""8o
            
            
            
    b 11
    .o8      
    "888      
    888oooo. 
    d88' `88b
    888   888
    888   888
    `Y8bod8P'
    
""".trimIndent()

fun main() {
    fun String.isLetterStart() = this.matches(Regex("^[a-zA-Z] [0-9]{1,2}"))
    val letters = mutableListOf<Letter>()
    var lineCount = 0
    var char = ""
    var asciFontLetter = ""
    font.lines().forEach { line ->
        if (lineCount > 0) {
            if (lineCount == 8) {
                lineCount = 0
                letters  = Letter(char, asciFontLetter)
                asciFontLetter = "\n"
            } else {
                lineCount  
                asciFontLetter  = line   "\n"
            }
        }
        if (line.isLetterStart() && lineCount == 0) {
            char = line.substringBefore(" ")
            lineCount  
        }
    }
    println(letters)
}


data class Letter(val char: String, val bitmapFontLetter: String)

  • Related