Python初学者如何将文本中的数字单词转换为电话号码输出到文件
数字单词转电话号码实现问题
问题背景
我是仅学习了3个月Python的初学者,本次学校作业要求读取包含数字单词(例如:three、oh、five、nine等)的文本文件,将内容转换为电话号码后写入单独的文件中。思考许久也没想出适合初学者的简单实现代码,希望得到帮助。
梳理的IPO实现逻辑
- 输入:以只读模式打开文本文件
- 处理:将文本文件内容拆分得到单词列表,将每个单词转换为对应的数字,再把所有数字拼接为字符串
- 输出:将存储电话号码的字符串写入目标文件
我目前无法将上述逻辑转换为可运行的代码。
输入文件内容示例
- two three seven oh nine eight oh
- eight one eight four three seven two nine six three
- one five oh three four seven seven two five seven two
- two nine six two three five oh
- five two oh four four seven nine eight two one
- one eight oh oh five five five one two one two
- four three seven two nine six three
最终可运行代码
di = {"oh":0,"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9} c="" infile=open("digit_words.txt","r") outfile=open("digit_strings.txt","w") l=infile.readlines() for line in l: words=line.split() for nos in words: c+=str(di[nos]) print(c, file=outfile) print("\n") c="" infile.close() outfile.close()
输出文件内容示例
- 2370980
- 8184372963
- 15034772572
- 2962350
- 5204479821
- 18005551212
- 4372963
内容的提问来源于stack exchange,提问作者sylllx
相关产品推荐
相关产品推荐

