在文本文件中查找整数,在新的文本文件中重写为字符串Python



我正试图编写一个函数,逐行查看文本文件,其中包含诸如"2加6=8"之类的字符串。我希望这个程序遍历文本文件,如果它找到一个整数,它会将其更改为整数的拼写名称。

因此,在本例中,它打开文件,读取它,看到2加6=8,并将其更改为2加6=8。

有人能帮我吗?

感谢

如果有任何超过9的数字,这将很困难,但如果没有。。。

from_ = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
to = ['zero','one','two','three','four','five','six','seven','eight','nine']
table = str.maketrans(dict( zip(from_, to) ))
line = "2 plus 6 = 8"
output = line.translate(table)
# output == "two plus six = eight"

你可以通过以下操作构建它来查看文件:

def spellnumbers(line):
    from_ = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    to = ['zero','one','two','three','four','five','six','seven','eight','nine']
    table = str.maketrans( dict(zip(from_, to)) )
    return line.translate(table)
with open('path/to/input/file.txt') as inf and open('path/to/output/file.txt', 'w') as outf:
    for line in inf:
        outf.write(spellnumbers(line))
        outf.write('n')

这基本上只是建立了一个形式的字典:

{ "0": "zero", "1": "one", ... , "9": "nine" }

然后从中构建一个翻译表,并在翻译过程中运行字符串。

如果你确实有超过9的数字,那么你会遇到"10 + 2 = 12"变成"onezero + two = onetwo"的问题。这个问题是不平凡的。

编辑

我碰巧看到你的转发中提到你不允许使用"表格或词典",这是一个愚蠢的要求,但没关系。如果这是真的,那么这一定是学校的作业,在这种情况下,我不会为你做家庭作业,但可能会引导你朝着正确的方向前进:

def spellnumbers(line):
    # 1. split the line into words. Remember str.split
    # 2. create an empty string that you can write output to. We'll
    #    use that more in a minute.
    # 3. iterate through those words with a for loop and check if
    #    word == '1':, elif word == '2'; elif word == '3', etc
    # 4. for each if block, add the number's name ("one", "two") to
    #    the output string we created in step 2
    # 5. you'll want an else block that just writes the word to
    #    the output string
    # 6. return the output string
f = open('path/to/file.txt')
lines = f.readlines() # this is ugly, but you're a beginner so we'll stick with this
for line in lines:
    stripped_line = line.strip() # removes leading and trailing whitespace e.g. n
    print(spellnumbers(line))
    # are you printing the output? How are you displaying it?

最新更新