[英]Vertically aligned str to reversed horizontal sequence
一旦我得到了我需要的所有字符串,下一步就是找到所有垂直对齐的字符串整数并将它们彼此相邻放在同一行中,而不是将每个 str 单独放置,然后将它们反转
文本文件:
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
所需的 output:
8510725
8510723
8547169
8510791
8542798
8542799
代码:
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()
当然,现在我以这种方式分别获得了所需的结果,但是,我有兴趣为这个问题获得更优雅的解决方案。 谢谢!
您可以遍历文件的每一行,如果没有换行符的行是一个数字,并且只有一个数字,则将其添加到我们的数字字符串中。 如果我们到达新行,检查数字字符串是否有任何数据,将其反转并将其存储在我们找到的数字列表中,然后将数字字符串重置为空。
这个解决方案也不是硬编码要查找的数字数量和要查看的行。 无论文件中有多少数字,它都应该缩放。
numbers = []
with open("out2.txt") as file:
number = ""
for line in file:
content = line.strip()
if content.isdigit() and len(content) == 1:
number += content
elif content == "" and number != "":
numbers.append(number[::-1])
number = ""
print(*numbers, sep="\n")
OUTPUT
8510725
8510723
8547169
8510791
8542798
8542799
下面的代码可以解决问题:
numbers = []
numbers_converted = []
with open('txtfile.txt','r') as f:
for line in f.readlines():
if len(line) == 2:
numbers.append(line.replace('\n', ''))
numbers = [numbers[i*7:i*7+7] for i in range(7)] #The word is 7 char big
numbers.pop() #Get rid of the last list because it is empty
for number in numbers:
number.reverse()
numbers_converted.append(int("".join(number)))
print(numbers_converted)
输出上面的代码:
[8510725, 8510723, 8547169, 8510791, 8542798, 8542799]
您可以使用内置的re
模块:
import re
with open('pgone.txt','r') as ifile:
for line in re.findall('\d\n\d\n\d\n\d\n\d\n\d\n\d', ifile.read()):
print(line.replace('\n', '')[::-1])
Output:
8510725
8510723
8547169
8510791
8542798
8542799
解释:
模式\d\n\d\n\d\n\d\n\d\n\d\n\d
告诉正则表达式返回file.read()
中由换行符分隔的 7 位数字的所有子字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.