Python Forum
Coordinates from a text file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Coordinates from a text file
#1
Hi i have to create a 2d game of sorts and to start it i need to create a function which reads in a text file and creates a list from each line.
and then from that line those characters are separated.
for example if the text file has
******F****
*****W*****
it needs to become
[****F****, *****W*****] and then
[[*,*,*,F,*,*,*,*],[*,*,*,*,W,*,*,*,*]]

from what ive heard you need to use a while loop with a nested while loop to achieve this but i just have no idea where to start.
Reply
#2
Check https://docs.python.org/3.3/tutorial/inp...ting-files

Use list(line_read_file) to convert into list
Reply
#3
(May-04-2020, 10:59 AM)anbu23 Wrote: Check https://docs.python.org/3.3/tutorial/inp...ting-files

Use list(line_read_file) to convert into list


sorry i have to create a another list within that list if that makes sense
Reply
#4
In Python sequences are iterable. Also a str is iterable.
A list, tuple, set, dict, ..., consumes iterables.

greeting = "Hello World"
print(list(greeting))
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
So you can use this, to split the chars of a line, which represents the row (y coordinates).

text = """
******F****
*****W*****
""".strip()
# the text has a leading '\n'
# and a tailing '\n'
# strip removes whitespaces from left and right side of a str
# also a newline is interpreted as whitespace.

matrix2d = [list(line.strip()) for line in text.splitlines()]
# iterate over lines, which are the rows
# make a list from each row, which represents the columns


# if you want to transpose the 2d matrix:
matrix2d_transposed = list(zip(*matrix2d))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
(May-04-2020, 11:20 AM)DeaD_EyE Wrote: In Python sequences are iterable. Also a str is iterable.
A list, tuple, set, dict, ..., consumes iterables.

greeting = "Hello World"
print(list(greeting))
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
So you can use this, to split the chars of a line, which represents the row (y coordinates).

text = """
******F****
*****W*****
""".strip()
# the text has a leading '\n'
# and a tailing '\n'
# strip removes whitespaces from left and right side of a str
# also a newline is interpreted as whitespace.

matrix2d = [list(line.strip()) for line in text.splitlines()]
# iterate over lines, which are the rows
# make a list from each row, which represents the columns


# if you want to transpose the 2d matrix:
matrix2d_transposed = list(zip(*matrix2d))

another way to sort of say what i need is
ls = ['string one' , 'string two']
ls2 = [[s,t,r,i,g, ,o,n,e], [,s,t,r,i,n,g, ,t,w,o]]

(May-04-2020, 12:10 PM)garry1415 Wrote:
(May-04-2020, 11:20 AM)DeaD_EyE Wrote: In Python sequences are iterable. Also a str is iterable.
A list, tuple, set, dict, ..., consumes iterables.

greeting = "Hello World"
print(list(greeting))
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
So you can use this, to split the chars of a line, which represents the row (y coordinates).

text = """
******F****
*****W*****
""".strip()
# the text has a leading '\n'
# and a tailing '\n'
# strip removes whitespaces from left and right side of a str
# also a newline is interpreted as whitespace.

matrix2d = [list(line.strip()) for line in text.splitlines()]
# iterate over lines, which are the rows
# make a list from each row, which represents the columns


# if you want to transpose the 2d matrix:
matrix2d_transposed = list(zip(*matrix2d))

another way to sort of say what i need is
ls = ['string one' , 'string two']
ls2 = [[s,t,r,i,g, ,o,n,e], [,s,t,r,i,n,g, ,t,w,o]]
**X**
* *
**Y**

thats what the board looks like i need to put it in cells if that makes sense
Reply
#6
text = '''******F****
*****W*****'''
print ("text =",text)
ls = text.splitlines()
print ("ls =",ls)
ls2 = [[letter for letter in line] for line in ls]
print ("ls2 =",ls2)
Reply
#7
(May-04-2020, 12:46 PM)TomToad Wrote:
text = '''******F****
*****W*****'''
print ("text =",text)
ls = text.splitlines()
print ("ls =",ls)
ls2 = [[letter for letter in line] for line in ls]
print ("ls2 =",ls2)


could i apply this to a text file ill send you the code i have for that
def read_lines(filename):
    try:
        file = open(filename, 'r')
        readfile = file.readlines()
        return list(readfile)

    except FileNotFoundError:                                            
        return "{} does not exist!".format(filename)
and the file the code opens contains this
**X**
* *
**Y**
Reply
#8
Strings are sorted by lexicographical order (also known as alphabetical order).

Here an example with some German words:
Output:
In [70]: sorted(random.sample(words, 10)) Out[70]: ['Bakterienzüchtung', 'Chrzowitz', 'Generalfragen', 'Latzrock', 'Prognosemodell', 'Reliefklischee', 'chaotisieren', 'dreireihig', 'erwünschtestes', 'kampfunfähigem'] In [71]: sorted(random.sample(words, 10)) Out[71]: ['Ablehnen', 'Attenschweiler', 'Bewahrheitung', 'Filzgarn', 'Rollin', 'Schneckengrün', 'Textilgürtelreifen', 'anpflanzender', 'herausgestrichenen', 'kostenschonendes']
words = ["Ca", "ca", "cA"]
print(sotred(words))
Output:
['Ca', 'cA', 'ca']
Python is "seeing" the chars as values and they are compared as values
words = ['Ca', 'cA', 'ca']
chars_as_int = [tuple(ord(c) for c in word) for word in sorted(words)]
print(chars_as_int)
Output:
[(67, 97), (99, 65), (99, 97)]
Python sorts by first letter, then second letter, ...

Do you want to sort via alphabet?

Uppercase letters are smaller in their value as Lowercase letters.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,128 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,679 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Converted Pipe Delimited text file to CSV file atomxkai 4 6,998 Feb-11-2022, 12:38 AM
Last Post: atomxkai
  [split] How to convert the CSV text file into a txt file Pinto94 5 3,359 Dec-23-2020, 08:04 AM
Last Post: ndc85430
  Saving text file with a click: valueerror i/o operation on closed file vizier87 5 4,403 Nov-16-2020, 07:56 AM
Last Post: Gribouillis
  saving data from text file to CSV file in python having delimiter as space K11 1 2,407 Sep-11-2020, 06:28 AM
Last Post: bowlofred
  Web Form to Python Script to Text File to zip file to web wfsteadman 1 2,146 Aug-09-2020, 02:12 PM
Last Post: snippsat
  Convert Excel file to Text file marvel_plato 6 19,728 Jul-17-2020, 01:45 PM
Last Post: marvel_plato
  Extracting hole-coordinates from a STEP-file Saksa 1 2,775 Jan-20-2020, 04:24 PM
Last Post: Larz60+
  Rename file from value in text file Nuge93 1 2,182 Jan-20-2020, 03:50 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020