[英]obfuscation of a text file using python - by reversing the words and inserting a specific number of random characters between them
[英]Reversing a text and find same words - python
我必須在python中編寫一些代碼,該代碼將從文本中讀取所有單詞,將它們反轉,然后找出其中的哪些在正常格式和反向格式中相同。 到目前為止,我已經做到了:
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)
但這是行不通的,因為如果我給一個文本多行,它只會處理最后一行,而實際上似乎並沒有顛倒任何內容。 請幫忙嗎?
您可以執行以下操作,可以使用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
如果您只想打印一次回文詞,則可以使用一組理解
print '\n'.join({w for w in open('file.txt).read().split() if w==w[::-1]})
請注意,我的答案不會過濾任何單個字母,標點符號等,換句話說,它取決於對單詞的寬泛定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.