我想使用python计算文本文件中回文数。但是我写的这个程序给我0而不是2

时间:2018-09-09 01:42:00

标签: python python-3.x python-2.7 count palindrome

我想使用python计算文本文件中回文数。但是我写的这个程序给我0而不是2 文字档:

Tattarrattat was coined by writer James Joyce in a book called Ulysses.
Aibohphobia is a joke term used to describe the fear of palindromes.

程序:

filename = "palindrome_test.txt"
x=0
#initiation
with open('palindrome_test.txt','r') as text:
    for line in text: #for loop
        line = line.split() #to split the line into words
        for i in range(0,100):
            if line[i] == line[i][::-1]: 
                x +=1 #increment

print(x)

1 个答案:

答案 0 :(得分:0)

您的代码中有两个错误。首先,一行中的单词数通常不是100。其次,大写字母不等于相应的小写字母。这是程序的更正版本:

count = 0 # x is never a good name
with open('palindrome_test.txt','r') as text:
    for line in text: 
        words = line.lower().split() #split the lowercased line into words
        for w in words:
            if w == w[::-1]: 
                count += 1 #increment

请注意,单词“ a”也是回文(它在您的文本中出现两次)。

您可以用列表理解替换for循环以获得更好看的程序:

count = 0
with open('palindrome_test.txt','r') as text:
    for line in text: 
        words = line.lower().split() #split the lowercased line into words
        count += sum(w == w[::-1] for w in words)