我是编程新手,所以我很迷茫。我目前正在学习 Python,我需要打开一个文本文件并将每个字母更改为字母表中的下一个字母(例如 a -> b、b -> c 等)。我将如何编写这样的代码?
2 回答
1
对于初学者来说,这听起来像是一个很好的问题。
你可能想看的东西:
该open()功能允许您打开文件并对其进行读/写。例如
https://docs.python.org/3/library/functions.html#open
with open('test.out', 'r+') as fi:
all_lines = fi.readlines() # Read all lines from the file
fi.write('this string will be written to the file')
# The file is closed at this point in the code; `with()` is a context manager, look that up
该os.replace()功能可让您用另一个文件覆盖一个文件。您可以尝试读取输入文件,写入新的输出文件,然后用新的输出文件覆盖输入文件;这会让你这样做。
https://docs.python.org/3/library/os.html#os.replace
用字符的下一个增量替换字符是一个有趣的转折,因为这不是很多 Python 程序员必须处理的事情。这是增加字符的一种方法:
x = 'c'
print(chr(ord(x) + 1)) # will print 'd'
不只是给出答案,这应该为您提供入门所需的部分,请随时提出更多问题。
于 2020-10-30T00:03:36.863 回答
0
我认为这将非常有效。我认为代码可以缩短,但我仍然不确定如何。不是有发言权的专家with open。
with open("(your text file path)", "r") as f:
data = f.readline()
new_data = ""
for x in range(len(data)):
i = ord(data[x][0])
i += 1
x = chr(i)
new_data += x
print(new_data)
with open("(your text file path)", "w") as f:
f.write(new_data)
您必须将字母更改为数字,以便将它们加一,然后再将它们改回字母。这应该有效。
于 2020-10-30T00:04:00.517 回答