Python 中的 TXT 文件替换

发布于 2024-11-26 02:24:33 字数 150 浏览 0 评论 0原文

我对编程非常陌生,我有一个简单的问题,我只是不知道语法。我有一个常规文本文件,我想用它的所有字母替换数字。即如果我找到“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

妄想挽回 2024-12-03 02:24:33

例如

mappings = { "a" : "1", "b" : "2" }

f = open("myfile.txt")
for line in f:
     for oldc, newc in mappings.items():
         line = line.replace(oldc, newc)

     print line

E.g.

mappings = { "a" : "1", "b" : "2" }

f = open("myfile.txt")
for line in f:
     for oldc, newc in mappings.items():
         line = line.replace(oldc, newc)

     print line
感受沵的脚步 2024-12-03 02:24:33

使用转换表, string.maketranss.translate

import string
tr_from = string.lowercase

# replace 'a' with 1, ... 'i' with '9', 'j' with '0', 'k' with '1'
# change the '(i+1)%10' part if you want different behavior
tr_to = "".join(str((i+1)%10) for i in xrange(len(tr_from)))

assert len(tr_from) == len(tr_to)

# handling lowercase and uppercase
tr_table = string.maketrans(tr_from + tr_from.upper(), tr_to + tr_to)

with open('infilename', 'r') as infile:
  with open('outfilename', 'w') as outfile:
    # this reads the entire file into memory
    output = infile.read().translate(tr_table)
    outfile.write(output)

按行读取文件而不是全部读入内存:

for line in infile:
  outfile.write(line.translate(tr)table))

Using translation tables, string.maketrans and s.translate:

import string
tr_from = string.lowercase

# replace 'a' with 1, ... 'i' with '9', 'j' with '0', 'k' with '1'
# change the '(i+1)%10' part if you want different behavior
tr_to = "".join(str((i+1)%10) for i in xrange(len(tr_from)))

assert len(tr_from) == len(tr_to)

# handling lowercase and uppercase
tr_table = string.maketrans(tr_from + tr_from.upper(), tr_to + tr_to)

with open('infilename', 'r') as infile:
  with open('outfilename', 'w') as outfile:
    # this reads the entire file into memory
    output = infile.read().translate(tr_table)
    outfile.write(output)

To read the file in lines instead of all into memory:

for line in infile:
  outfile.write(line.translate(tr)table))
虚拟世界 2024-12-03 02:24:33

这是一个过于复杂的答案,但它有几个有用的 Python 概念,您应该在某个阶段学习这些概念。这是简单的版本:

with open(<path to file>) as f:
    for line in f:
        for char in line:
            if char.isalpha():
                print ord(char) - ord("a") + 1

第一行处理打开(和关闭)文件。第二个迭代文件的所有行。第三个迭代行中的每个字符。第四个检查该字符是否是字母(例如“.”的数量是多少?)。第五个实现了魔法:ord 将字母更改为其 ASCII 代码,即一个整数。由于代码不是从 1 开始,因此您必须先减去“a”的代码。


作为稍后的练习,这里有一个更通用的版本,它接受任何字符串并一次产生一个字符串中的字符。如果您想让我解释,请告诉我。

>>> def transformed(it):
...     it = iter(it)
...     for char in it:
...             if char.isalpha():
...                     yield ord(char) - ord("a")
...
>>> list(transformed("hello, world"))
[7, 4, 11, 11, 14, 22, 14, 17, 11, 3]

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:

with open(<path to file>) as f:
    for line in f:
        for char in line:
            if char.isalpha():
                print ord(char) - ord("a") + 1

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 yields the characters in the string one at a time. Let me know if you want me to explain it.

>>> def transformed(it):
...     it = iter(it)
...     for char in it:
...             if char.isalpha():
...                     yield ord(char) - ord("a")
...
>>> list(transformed("hello, world"))
[7, 4, 11, 11, 14, 22, 14, 17, 11, 3]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文