Вопрос

I have a .txt file which consist of;

A!
B@
C3

etc. I want to import each character as a different variable, such as the end result being that e.g.

line1_char1 = "A"
line1_char2 = "!"
line2_char1 = "B"

ect. Does anyone know how to code this properly in python?

I think I need to do something along the lines on;

ci = open("myfile.txt")
line1_char1 = ci.read(1,1)
line1_char2 = ci.read(1,2)
line2_char1 = ci.read(2,1)
ci.close

ect. Am I nearly correct on this and what do I need to do to get it working?

Это было полезно?

Решение

my favorite way to read characters from a file is by using a list comprehension like so:

f=open(textfile, 'r')
while 1:
    line=f.readline().strip() #this gets rid of the newline character
    if line=='':# if there are no more lines, quit looping
        f.close()
        break
    characters=[line[i] for i in range(len(line))] this splits up every character of the line into its own item in a list.  NOTE THIS WILL INCLUDE SPACES AND PUNCTUATION

As for using those characters as variable names, I think you may want to try a dictionary. for every character you read from the file, assign that value as a key in a dictionary like this

tempdict=dict()
f=open(textfile, 'r')
while 1:
    x=f.readline().strip()
    if x=='':
        f.close()
        break
    x=[x[i] for i in range(len(x))]
    for node in x:
        tempdict[node]=''

now you can call up each one of those characters by calling

tempdict[charactername]

and either assigning a value or retrieving a value.


UPDATE

characterslist=[]
f=open('putyourtextfilenamehere','r')
while 1:
    x=f.readline().strip()
    if x=='':
        f.close()
        break
    x=[x[i] for i in range(len(x))]
    for j in x:
        characterslist.append(j)

that should read each line and save the characters into a list called characterslist

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top