[英]Reversing a text and find same words - python
I have to write some code in python that will read all words from a text, reverse them and find which of them are the same in normal and reverse format. 我必须在python中编写一些代码,该代码将从文本中读取所有单词,将它们反转,然后找出其中的哪些在正常格式和反向格式中相同。 So far, I 've done this: 到目前为止,我已经做到了:
filename=raw_input("enter the file name: ")
fop=open(filename)
for line in fop:
words=line.split()
li=[]
li.extend(words)
size=len(li)
for i in range(0,size/2):
li[i], li[size-1-i] = li[size-1-i], li[i]
`enter code here`''.join(li)
but it doesn 't work, because if i give a text with more than one lines, it only processes the last line and doesn 't actually seem to reverse anything. 但这是行不通的,因为如果我给一个文本多行,它只会处理最后一行,而实际上似乎并没有颠倒任何内容。 Some help please? 请帮忙吗?
You can just do the following , you can check for reverse with word == word[::-1]
that word[::-1]
is reverse indexing : 您可以执行以下操作,可以使用word == word[::-1]
来检查word[::-1]
是否为反向索引:
filename=raw_input("enter the file name: ")
with open(filename) as f :
for line in f:
for word in line.split() :
if word == word[::-1]:
print word
If you want to print just once the palindrome words you can use a set comprehension 如果您只想打印一次回文词,则可以使用一组理解
print '\n'.join({w for w in open('file.txt).read().split() if w==w[::-1]})
Note that my answer doesn't filter any single letters, punctuation etc, in other words it depends on a loose and broad definition of what is a word. 请注意,我的答案不会过滤任何单个字母,标点符号等,换句话说,它取决于对单词的宽泛定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.