简体   繁体   English

反转文本并找到相同的单词-python

[英]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.

相关问题 使用 python 混淆文本文件 - 通过反转单词并在它们之间插入特定数量的随机字符 - obfuscation of a text file using python - by reversing the words and inserting a specific number of random characters between them 反转 Python 字符串中的单词(包括标点符号) - Reversing words in a Python string (including punctuation) 在 Python 中随机反转列表列表中的一半单词 - Reversing half the words in a list of lists randomly in Python Python-查找文本文件中同一行中每个可能的单词对出现频率的最有效方法? - Python - Most efficient way to find how often each possible pair of words occurs in the same line in a text file? 如何在python的文本分析中找到连接词? - how find the connecting words in text analysis in python? Python正则表达式查找文本中的所有单词 - python regex find all words in text 如何使用Python在文本文件中查找单词 - How to find words in text files with Python 从与给定单词相同模式的文本中查找字符串 - Find strings from text same pattern as given words 如何在Python中反转字符串中的单词(而不是反转整个字符串)? - How to reverse the words inside a string in Python (not reversing whole string)? 反转Python中文件中的文本列 - Reversing a column of text from a file in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM