我想用python计算文本文件中的Palindromes数量。但我写的这个程序给了我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)
您的代码中有两个错误。首先,一行中的单词数通常不是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)