0

I need to grab all the palindrome lines (spelled same forwards and backwards) in a text file from the linux command line. I do not think you can use just one command to do this since you have to check for any length of line. So I do not know of a way to do this other than making a script (correct me if I'm wrong). So what I did is grab all of the lengths of lines and did a grep command that would check for lines that are that long:

import os

ex_front = "egrep -i '^"
ex_middle_front = ""
ex_middle_back = ""
ex_back = "$' textfile.txt"

textFile = open("textfile.txt", "r")
stringList = textFile.readlines()
lengthList = set([])

for line in stringList:
    lengthList.add(len(line))

for x in lengthList:
    ex_middle_front = ""
    ex_middle_back = ""

    for i in range(int(x/2), 0, -1):
        ex_middle_front += "(.)"
        ex_middle_back += "\\" + str(i)

    if x % 2 == 0:
        ex_middle = ""
    else:
        ex_middle = "."

    os.system(ex_front + ex_middle_front + ex_middle + ex_middle_back + ex_back)

This works, but I am wondering if there is a better solution.

Slaknation
  • 2,124
  • 3
  • 23
  • 42

2 Answers2

4

Here's one way:

def is_palindrome(x):
    return x == x[::-1]

with open('so_palindromes.txt', 'r') as f:
    for line in map(lambda x: x.rstrip(), f):
        if is_palindrome(line):
            print(line)

Test file:

lol
not
really
a
palindrome
yay
hah

Output:

lol
a
yay
hah
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
1

I'm not sure why you're going for regular expressions here. Go back to the definition of a palindrome: spelled same forwards and backwards. ie. the line will be the same as the line backwards. Therefore all you need to check in the code is a reversed version of the line against the line. Example code below with comments:

palindromes = []
with open('textfile.txt') as f:
    for line in f:

        # remove trailing newlines
        line = line.strip()

        # 'if line' makes sure the line isn't empty
        # line[::-1] is shorthand for reversing the string
        if line and line == line[::-1]:

            # so here line is a palindrome
            # do what you want with it
            palindromes.append(line)

print(palindromes)