回文比较无法检测到某些病例

问题描述

如果单词/行是回文,我想打印True。 该代码从文本文件中读取文本(使用sys.argv [1])。 我不明白为什么它只检查第一行。

文本文件

racecar
AddE
HmllpH
Was it a car or a cat I saw
Hannah
T can arise in context where language is played wit
Able was I ere I saw Elba
Doc note I dissent A fast never prevents a fatness I diet on cod

代码

import sys
filename = sys.argv[1]

with open(filename,"r") as f:
    text = f.readline().strip().lower()

    while text:
        palindrome = True
        i = 0
        while i < len(text) / 2:
            if text[i] != text[len(text) - 1 - i]:
                palindrome = False
            i += 1
        if palindrome:
            print(True)
        text = f.readline().strip()

输出

True

解决方法

  1. 为什么只打印第一行?

只有第一行是区分大小写的回文。

  1. 代码修复:

关于您所看到的内容的一些解释:

2.1。循环for text in map(str.strip,f)意味着我们要遍历文件f行,并在每行上应用str.strip()方法。

2.2。 text.upper()可以将文本转换为统一的大写字母,以进行常见比较。

2.3。 text_upper[::-1]反转文本:奇怪的[::-1]索引符号表示我们将所有元素向后移动一步(因此为-1)。

import sys
filename = 'outfile.txt'

with open(filename,"r") as f:
    for text in map(str.strip,f):
        text_upper = text.upper()
        if text_upper == text_upper[::-1]:
            print(f'{text} is palindrom!')
,

它会检查所有行,但只有第一种情况返回True,因为其他行没有.lower()。您必须将最后一行更改为text = f.readline().strip().lower()