gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:47:23 26 4
gpt4 key购买 nike

我正在尝试编写一个逐行查看文本文件的函数,其中包含诸如“2 plus 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?

关于python - 在文本文件中查找整数在新文本文件中重写为字符串 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23071413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com