Python 中的 TXT 文件替换
我对编程非常陌生,我有一个简单的问题,我只是不知道语法。我有一个常规文本文件,我想用它的所有字母替换数字。即如果我找到“a”或“A”,我想替换数字“1”。如果我找到“b”或“B”,我想替换数字“2”等。有人可以帮助我吗,我知道这是最基本的,但我正在尝试自己学习编程,这非常困难。谢谢你!
I very new to programming and I have a simple problem that I just do not know the syntax to. I have a regular text file that I want to substitute all of the letters for numbers. i.e. if I find an "a" or an "A", I want to substitute the number "1". If I find a "b" or "B" I want to substitute the number "2" ect. Can someone help me with this, I know it is most basic but I am trying to learn to program on my own and it is quite difficult. Thank-you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
例如
E.g.
使用转换表, string.maketrans 和 s.translate:
按行读取文件而不是全部读入内存:
Using translation tables, string.maketrans and s.translate:
To read the file in lines instead of all into memory:
这是一个过于复杂的答案,但它有几个有用的 Python 概念,您应该在某个阶段学习这些概念。这是简单的版本:
第一行处理打开(和关闭)文件。第二个迭代文件的所有行。第三个迭代行中的每个字符。第四个检查该字符是否是字母(例如“.”的数量是多少?)。第五个实现了魔法:
ord
将字母更改为其 ASCII 代码,即一个整数。由于代码不是从 1 开始,因此您必须先减去“a”的代码。作为稍后的练习,这里有一个更通用的版本,它接受任何字符串并一次产生一个字符串中的字符。如果您想让我解释,请告诉我。
This is something of an overcomplicated answer, but it has several useful Python concepts which you should at some stage learn. Here's the simple version:
The first line handles opening (and closing) the file. The second iterates over all the lines of the file. The third iterates over each character in the line. The fourth checks to see whether the character is a letter or not (what is the number of ".", say?). The fifth does the magic:
ord
changes a letter into its ASCII code, which is an integer. Since the codes don't start at one, you have to subtract the code of "a" first.As an exercise for later, here's a more generic version that takes any string and
yield
s the characters in the string one at a time. Let me know if you want me to explain it.