[英]How do I split text from a text file at newlines?
我需要加密一條消息。 該消息如下,它被保存在一個名為assignmenttest.txt的文件中
Hi my name is Allie
I am a Junior
I like to play volleyball
我需要程序來加密每一行並保持其格式,因此,我編寫了以下程序:
fileInputName = input("Enter the file you want to encrypt: ")
key = int(input("Enter your shift key: "))
outputFileName = input("Enter the file name to write to: ")
fileInputOpen = open(fileInputName, "r")
message = fileInputOpen.read()
alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
shiftedStart = alphabet[len(alphabet) - key:]
shiftedEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedStart + shiftedEnd
encryptedMessage = ""
for character in message:
letterIndex = message.split("\n")
letterIndex = alphabet.find(character)
encryptedCharacter = shiftedAlphabet[letterIndex]
#print( "{0} -> {1}".format(character, encryptedCharacter))
encryptedMessage += encryptedCharacter
print("The encrypted message is: {0}".format(encryptedMessage))
outputFile = open( outputFileName, "w")
print(encryptedMessage, file=outputFile)
outputFile.close()
print("Done writing encrypted message to file {0}".format(outputFileName))
我嘗試在\\ n處使用split,但是輸出未格式化為三行,而是全部為一個長串的加密字母。
關於如何在正確的位置分割加密郵件並使其顯示出來的任何想法? 我嘗試了多種拆分方法,但均無效果。 非常感謝。
不必在'\\n'
處拆分,而是在遇到一個字符時,可以將message
中所有非alphabet
的字符附加到encryptedMessage
message
中。
for character in message:
if !(character in alphabet):
encryptedMessage += character
continue # this takes back to begin of the loop
letterIndex = alphabet.find(character)
encryptedCharacter = shiftedAlphabet[letterIndex]
#print( "{0} -> {1}".format(character, encryptedCharacter))
encryptedMessage += encryptedCharacter
正如其他答案所說,您可以替換
fileInputOpen = open(fileInputName, "r")
message = fileInputOpen.read()
同
with open(fileInputName, "r") as f:
messages = f.readlines()
這樣, messages
將是一個字符串列表,其中每個字符串都是輸入文件中一行的文本。 然后,對消息中每個字符的循環進行一些細微修改,就可以對messages
列表中的每個字符串進行加密。 在這里,我換成你encryptedMessage
與currentEncryptedMessage
並補充encryptedMessages
,持續跟蹤每個字符串的加密版本列表messages
。
encryptedMessages = []
currentEncryptedMessage = ""
for message in messages:
for character in message:
... # same as code provided
currentEncryptedMessage += encryptedCharacter
encryptedMessages.append(currentEncryptedMessage)
寫入文件時,您可以遍歷encryptedMessages
每個元素以逐行打印。
with open( outputFileName, "w") as outputFile:
for message in encryptedMessages:
print(message, file=outputFile)
因此,您的輸出文本文件將保留輸入文件中的換行符。
而不是一次全部讀取文件。 分別閱讀各行。
f = open("file.txt")
for i in f.readlines():
print (i)
嘗試更改:
message = fileInputOpen.read()
至
message = fileInputOpen.readlines()
這將使您的文件讀取逐行處理文件。 這將使您可以先逐行進行處理。 除此之外,如果要加密每個字符,則需要另一個for循環用於字符。
alphabet
; with open...
是在python中讀寫文件的推薦方法。 這是一種方法:
import os
import string
fileInputName = input("Enter the file you want to encrypt: ")
while not os.path.exists(fileInputName):
fileInputName = input("{} file doesn't exist.\nEnter the file you want to encrypt : ".format(fileInputName))
key = int(input("Enter your shift key (> 0): "))
while key < 1 :
key = int(input("Invalid shift key value ({}) \nEnter your shift key (> 0): ".format(key)))
fileOutputName = input("Enter the file name to write to: ")
if os.path.exists(fileOutputName) :
ow = input("{} exists, overwrite? (y/n): ".format(fileOutputName))
if not ow.startswith("y"):
fileOutputName = input("Enter the file name to write to: ") # asks for output filename again
alphabet = string.ascii_letters + " "
shiftedStart = alphabet[len(alphabet) - key:]
shiftedEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedStart + shiftedEnd
with open(fileOutputName, "a") as outputFile: # opens out file
with open(fileInputName, "r") as inFile: # opens in file
for line in inFile.readlines(): # loop all lines in fileInput
encryptedCharacter = ""
for character in line: # loop all characters in line
if character in alphabet: # un-shift only if character is present in `alphabet`
letterIndex = alphabet.find(character)
encryptedCharacter += shiftedAlphabet[letterIndex]
else:
encryptedCharacter += character # add the original character un-shifted
outputFile.write("{}".format(encryptedCharacter)) # append line to outfile
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.