简体   繁体   中英

How to convert lines read from a file into one long string?

I am trying to create a postfix calculator. I have a file named expressions.txt that comes with six postfix operations. When I read the files in, it gives me a list with a bunch of new lines. For example,

f = open("expressions.txt", "r")
expression = f.readlines()

gives me:

['5 4 3 + 2 * -\n', '8 5 *\n', '20 5 /\n', '3 8 6 + *\n', '3 4 + 9 - 12 +\n', '9 3 2 1 + + /\n', '3 + 4\n', '* 3 4 5 + *\n', '4 9 1 3 + -\n', 'h 3 +\n']

I need

['5 4 3 + 2 * 8 5 * 20 5 / 3 8 6 ... ]

and so on and so on. I am trying to figure out how to instead of get each line into a list, i need each line to be joined into one big string.

EDIT: Okay, here is the full code.

from ArrayStack import *

evaluation = Stack()

def main():
   count = 0
   f = open("expressions.txt", "r")
   l = f.readlines()
   for char in l:
     char.replace("\n","")
     char.split(' ')
     evaluation.push(char)
   print(evaluation.data)

It is still not working to where I can push each number and operation onto the stack.

If you can control the input file, this is easiest with tr on unix:

tr '\n' '' < input_file

If you have to use python, this will work:

with open('file') as f:
  expression = f.read().replace('\n', '')

Notice that I used f.read() instead of f.readlines() . f.read() returns a string rather than a list of strings, which saves you re-joining the lines later.

>>> l = ['5 4 3 + 2 * -\n', '8 5 *\n', '20 5 /\n', '3 8 6 + *\n', '3 4 + 9 - 12 +\n', '9 3 2 1 + + /\n', '3 + 4\n', '* 3 4 5 + *\n', '4 9 1 3 + -\n', 'h 3 +\n']
>>> s ="".join(i.replace("\n","") for i in l)
'5 4 3 + 2 * -8 5 *20 5 /3 8 6 + *3 4 + 9 - 12 +9 3 2 1 + + /3 + 4* 3 4 5 + *4 9 1 3 + -h 3 +'

Also if you want to take it one step further to prepare for parsing (if that's what you're going for) you can do this

>>> s.replace(" ","")
'543+2*-85*205/386+*34+9-12+9321++/3+4*345+*4913+-h3+'
expressions = "".join(line.rstrip("\n") for line in open("expressions.txt", "r"))
expression = ['5 4 3 + 2 * -\n', '8 5 *\n', '20 5 /\n', '3 8 6 + *\n', '3 4 + 9 - 12 +\n', '9 3 2 1 + + /\n', 
          '3 + 4\n',
        '* 3 4 5 + *\n', '4 9 1 3 + -\n', 'h 3 +\n']

expression = [''.join([char for char in ''.join(expression) if char != '\n'])]

Output:

["5 4 3 + 2 * -8 5 *20 5 /3 8 6 + *3 4 + 9 - 12 +9 3 2 1 + + /3 + 4* 3 4 5 + *4 9 1 3 + -h 3 +"]

Instead of replace , strip can serve you too:

with open("expressions.txt") as f:
    expression = "".join(line.strip("\n") for line in f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM