[英]How to return the each unique character per line in a list in Python?
I have a file (secret_message.txt) in the likes of: 我有一个类似的文件(secret_message.txt):
Yap Cat Hat
Two Ants Like Two Ant Like Kids
Ants Like Cat Two
and I want to read each line individually and replace only one occurrence of: 我想分别阅读每一行,并只替换以下内容之一:
Yap with Y
Cat with O
Hat with U
Two with T
Ants with A
Like with L
Kids with K
while ignoring repeated words, such that the output file reads: 而忽略重复的单词,以便输出文件读取:
YOU
TALK
ALOT
I plan to re-use the same secret code language for future messages, however, so I don't need to remake a new translation dictionary each time. 但是,我计划为以后的消息重用相同的密码语言,因此,我不需要每次都重新制作新的翻译词典。
Any suggestions on how to do this most efficiently would be tremendously appreciated! 任何有关如何最有效地执行此操作的建议将不胜感激!
Below is what I have tried: 以下是我尝试过的方法:
#!/usr/bin/env python
import os
import glob
import fileinput
filename = 'secret_message.txt'
with open(filename,'r') as f:
f2 = f.read().split('\n')
for line in f2:
f3 = line.replace("Yap","Y",1)
f3 = line.replace("Cat","O",1)
f3 = line.replace("Hat","U",1)
f3 = line.replace("Two","T",1)
f3 = line.replace("Ants","A",1)
f3 = line.replace("Like","L",1)
f3 = line.replace("Kids","K",1)
with open('secret_answer.txt', 'w') as f:
f.write(f3)
Maybe someone has a better solution, but if you build a list of potential keys before translating each line, then you can delete each key you use so that you ignore duplicates. 也许有人有更好的解决方案,但是如果您在翻译每一行之前先建立了一个潜在键的列表,则可以删除使用的每个键,从而忽略重复项。
TRANSLATOR = {
"Cat": "O",
...
}
def translate(line):
keys = set(TRANSLATOR)
secretStr = ""
for word in line.split(" "):
if word in keys:
secretStr += TRANSLATOR[word]
keys.remove(word)
return secretStr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.