def encrypt():
while True:
try:
userinp = input("Please enter the name of a file: ")
file = open(f"{userinp}.txt", "r")
break
except:
print("That File Does Not Exist!")
second = open("encoded.txt", "w")
for line in file:
reverse_word(line)
def reverse_word(line):
data = line.read()
data_1 = data[::-1]
print(data_1)
return data_1
encrypt()
我目前應該制作一個以某種方式加密文本檔案的程式,我嘗試使用的一種方法是反轉文本檔案中的行序列。我的所有其他功能已經完成,使用“for line in file”,其中“line”被轉移到每個單獨的功能,然后為了加密而改變,但是當試圖在這里做同樣的事情來顛倒順序時檔案中的行,我得到一個錯誤
“str”物件沒有屬性“read”
我嘗試使用與下面相同的順序,但轉而保留檔案,它可以作業,但我希望擁有它,以便當我從檔案中保留單獨的行時它可以作業,就像使用我目前擁有的其他功能(或者更簡單地說,在 for 回圈中具有此功能)。
有什么建議么?謝謝!
uj5u.com熱心網友回復:
您是要顛倒行的順序還是每行中單詞的順序?
可以通過簡單地讀取行并使用內置reverse函式來反轉行:
lines = fp.readlines()
lines.reverse()
如果您嘗試反轉單詞(實際單詞,而不僅僅是每行中的字串),您將需要做一些正則運算式來匹配單詞邊界。
否則,只需反轉每一行就可以像這樣完成:
lines = fp.readlines()
for line in lines:
chars = list(line)
chars.reverse()
uj5u.com熱心網友回復:
我認為您所指的錯誤在此函式中:
def reverse_word(line):
data = line.read()
data_1 = data[::-1]
print(data_1)
return data_1
你不需要呼叫read(),line因為它已經是一個字串;read()在檔案物件上呼叫以將它們轉換為字串。做就是了:
def reverse_line(line):
return line[::-1]
它會反轉整條線。
如果您想反轉行中的單個單詞,同時保持它們在行內的相同順序(例如將“the cat sat on a hat”變成“eht tac tas no a tah”),那就是:
def reverse_words(line):
return ' '.join(word[::-1] for word in line.split())
如果您想顛倒單詞的順序而不是單詞本身(例如將“the cat sat on a hat”變成“hat a on sat cat the”),那就是:
def reverse_word_order(line):
return ' '.join(line.split()[::-1])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/461283.html
標籤:Python python-3.x 功能 for循环 逆转
上一篇:將下一個數字添加到R中向量中的前一個數字,For回圈
下一篇:洗掉串列中的節點
