gpt4 book ai didi

python Linux : Grab all lines that can be spelled forward and backwards in a text file

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:34 24 4
gpt4 key购买 nike

我需要从 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)

这行得通,但我想知道是否有更好的解决方案。

最佳答案

这是一种方法:

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

关于 python Linux : Grab all lines that can be spelled forward and backwards in a text file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50731499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com