Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

python - Vertically aligned str to reversed horizontal sequence

Once I get all the strings that I need, the next step would be to locate all the vertically aligned string integers and put them next to each other in the same line instead of each str to be in separate and later reverse them

text file:

night train whistles stars
over a nation under
mad temporal czars

round lumps of cells grow:

1234567     Info1 
1234567     Info2 
1234567     Info3 

5
2
7
0
1
5
8

3
2
7
0
1
5
8

9
6
1
7
4
5
8

1
9
7
0
1
5
8

8
9
7
2
4
5
8

9
9
7
2
4
5
8

Info5
Info6

Desired output:

8510725 
8510723
8547169
8510791
8542798
8542799

code:

ifile = open('pgone.txt','r')
buffer = ifile.readlines()
temp = ""
listy = []

for e in buffer:
    temp += e.strip('""')
    if len(e) == 2:
        listy.append(e)


one = listy[0:7]
two = listy[7:14]
three = listy[14:21]
four = listy[21:28]
five = listy[28:35]
six = listy[35:]

one.reverse()
two.reverse()
three.reverse()
four.reverse()
five.reverse()
six.reverse()

Now of course I get the desired result separately in this manner, however, I would be interested to get more elegant solutions to this problem. Thanks!

question from:https://stackoverflow.com/questions/65902076/vertically-aligned-str-to-reversed-horizontal-sequence

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the built-in re module:

import re

with open('pgone.txt','r') as ifile:
    for line in re.findall('d
d
d
d
d
d
d', ifile.read()):
        print(line.replace('
', '')[::-1])

Output:

8510725
8510723
8547169
8510791
8542798
8542799

Explanation:

The pattern d d d d d d d tells regex to return all substrings in file.read() that are 7 digits separated by a newline.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...