我需要从linux命令行获取文本文件中的所有回文代码行(向前和向后拼写相同)。我认为您不能只使用一个命令来完成此操作,因为您必须检查任何长度的行。因此,除了编写脚本(如果我错了,请纠正我)之外,我不知道有什么方法可以做到这一点。所以我所做的是获取所有行的长度,并执行一个grep命令,该命令将检查有那么长的行:
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)
这是可行的,但我想知道是否有更好的解决方案。
发布于 2018-06-07 09:02:34
这里有一种方法:
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)
测试文件:
lol
not
really
a
palindrome
yay
hah
输出:
lol
a
yay
hah
发布于 2018-06-07 09:02:53
我不知道你为什么要在这里使用正则表达式。回到回文的定义:向前和向后拼写相同。即。这行将与向后的行相同。因此,您需要在代码中签入的只是该行的反转版本。下面是带有注释的示例代码:
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)
https://stackoverflow.com/questions/50731499
复制相似问题