Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import a text file as an array of characters

I have a text file that consists of some text.

I want to import this into an array consisting of characters, Ex: a file containing "Hello" would become

['h', 'e', 'l', 'l', 'o'].

I tried using loadtxt (which I usually use for reading data from files) but I think it can only handle actual data (with numbers and stuff). How do I do it?

like image 450
user2229219 Avatar asked Oct 15 '25 04:10

user2229219


2 Answers

This is the usual way to read an entire file:

with open("file") as f:
    content = f.read()

You can then call list(content) to get a list from the string.

like image 180
rninty Avatar answered Oct 17 '25 18:10

rninty


If you want to load strings using loadtxt:

import numpy as np
text = np.loadtxt(filepath, dtype = np.str)

As others are mentioning, there are other ways of doing this. Furthermore, you can access the individual characters of a string in much the same way as a list.

like image 38
Magsol Avatar answered Oct 17 '25 16:10

Magsol