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

时间:2014-04-14 22:19:11

标签: python

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

所以在这个例子中,它打开文件,读取它,看到2加6 = 8并将其更改为2加6 = 8。

有人可以帮助我吗?

由于

1 个答案:

答案 0 :(得分:2)

如果您有超过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? 此问题非常重要。

修改

我碰巧看到你的转发提到你不允许使用“表格或字典”,这是一种愚蠢的要求,但没关系。如果这是真的,那么这必须是学校的作业,在这种情况下,我不会为你做功课,但也许可以引导你朝着正确的方向前进:

{{1}}