0

I have the following code to join the file and trying to sort the file in ascending order before writing the result into the final .txt file. But it is showing string object has no attribute.

temp_list = ''
with open('temp.txt') as f:
out = [x for x in f.read().split("\n") if x.strip() != ""] 
for line1, line2 in list(zip(out, out[1:]))[::2]:
    line1 = line1 + ';'
    line2 = line2.split(' ')
    line = ''
    for x in range(1,len(line2)):
        line = line + line2[x] + ' '
    line = line[:-1] + '.' 
    temp_list += " ".join([line1, line]) + '\n'
    temp_list.sort()

with open('new.txt' , 'w') as file:
file.write(temp_list)

temp.txt

line1 Ron likes apple; mango
line5 Ana likes lyche; apple
line21 Tyson likes football; VolleyBall
line6 Mike likes singing; dancing
line245 Stephen likes playing; sleeping
line95 Rose likes dancing; singing

The order of the lines should be like

line1
line5
line6
line21
line95
line245

but not like

line1
line21
line245
line5
line6
line95

Any help would be appreciated ..Thank you

sri
  • 75
  • 8
  • Do all of your lines start with "Line"? – Hai Vu Jun 07 '20 at 19:06
  • @Hai Vu, Yeah..Each Line starts with line – sri Jun 07 '20 at 19:10
  • see https://stackoverflow.com/questions/4836710/is-there-a-built-in-function-for-string-natural-sort – Stef Jun 07 '20 at 19:11
  • Does this answer your question? [Is there a built in function for string natural sort?](https://stackoverflow.com/questions/4836710/is-there-a-built-in-function-for-string-natural-sort) – Tsyvarev Jun 08 '20 at 12:39

4 Answers4

1
import re
with open("temp.txt", "r") as infile, open("new.txt", "w") as outfile:
    lines = infile.readlines()
    if not lines[-1].endswith("\n"):
        lines[-1] = lines[-1] + "\n"
    lines.sort(key=lambda x:int(re.findall(r"^[a-zA-Z]+(\d+)$", x.split()[0])[0]))
    outfile.writelines(lines)

You can try this using re.If the format is fixed, this will work.

Input text

Line1 Ron likes apple; mango line5 Ana likes lyche; apple line21 Tyson play football; VolleyBall line6 .......................... line245 ....................... line95 ............ line11 ......... line12 .......... line20 ..........

Output text

Line1 Ron likes apple; mango line5 Ana likes lyche; apple line6 .......................... line11 ......... line12 .......... line20 .......... line21 Tyson play football; VolleyBall line95 ............ line245 .......................

vks
  • 67,027
  • 10
  • 91
  • 124
1

I have this way:

with open('temo.txt','r') as f:
    l1 = [l.lstrip('line').split(' ',1) for l in f.readlines()]
    l2 = sorted([[int(a),b.strip()] for a,b in l1])
    for s in l2:
        print(f"line{s[0]} {s[1]}")

Output:

line1 Ron likes apple; mango
line5 Ana likes lyche; apple
line6 Mike likes singing; dancing
line21 Tyson likes football; VolleyBall
line95 Rose likes dancing; singing
line245 Stephen likes playing; sleeping

For the print error mentioned in the comments, try this:

print("line{} {}".format(s[0],s[1]))
Red
  • 26,798
  • 7
  • 36
  • 58
  • print statement is not working in linux. However, the code works in others. I do not want to strip the word line how will that work? – sri Jun 07 '20 at 20:46
  • Any idea about syntax for print statement in Linux cause it not not allowing "print()" this format – sri Jun 07 '20 at 21:36
  • @sri Fixed it ;) – Red Jun 07 '20 at 21:55
0

I don't have a real solution, but a workaround. I would save all lines in a dictionary and then just write this few lines:

def sort_lines(your_dictionary):
    temp_list = []
    for i in range (1, len(your_dictionary)+1):
        temp_list.append(your_dictionary[i])
    return temp_list

If your not sure if you have every number from 1 to the highest just change it a little bit:

def sort_lines(your_dictionary):
    temp_list = []
    for i in range (1, len(your_dictionary)+1):
        try:
            temp_list.append(your_dictionary[i])
        except:
            pass
    return temp_list
0

you can maybe use sorted

    temp = [
        "Line1 Ron likes apple; mango",
        "line5 Ana likes lyche; apple",
        "line21 Tyson play football; VolleyBall",
        "line6 ..........................",
        "line245 .......................",
        "line95 ............",
    ]


    def sort_fn(a):
        idx = a.find(" ")
        key_a = int(a[4:idx])
        return key_a

    sort = sorted(temp, key=sort_fn)
    print(sort)
D. Seah
  • 4,472
  • 1
  • 12
  • 20