我想用Python计算文本文件中回文数的数量,但是我写的程序给我的是0,而不是2。

2024-05-15 22:34:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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.

课程:

^{pr2}$

Tags: in程序byiswriter文本文件wascalled
1条回答
网友
1楼 · 发布于 2024-05-15 22:34:34

你的代码有两个错误。首先,一行的字数通常不是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循环,以获得更美观的程序:

^{pr2}$

相关问题 更多 >