【问题标题】:Search and replace numbers with words in file [duplicate]用文件中的单词搜索和替换数字[重复]
【发布时间】:2017-02-23 17:01:51
【问题描述】:
我有一个包含数字和字母的文件,我想将所有数字替换为单词(例如,将 8 转换为 8)。好吧,我只是没有办法检查我的文件中是否有数字。最有效的方法是什么?
【问题讨论】:
标签:
python
regex
file
search
replace
【解决方案1】:
以下应该可以工作,它读取输入文件,使用正则表达式查找所有数字,并使用 num2words 库将每个数字替换为文本:
import re
import num2words
with open('input.txt') as f_input:
text = f_input.read()
text = re.sub(r"(\d+)", lambda x: num2words.num2words(int(x.group(0))), text)
with open('output.txt', 'w') as f_output:
f_output.write(text)
num2words 库可以使用以下方式安装:
pip install num2words
因此,如果您的输入文本文件包含:
Today 1000 people wrote 500 words to make 321 questions.
输出将是:
Today one thousand people wrote five hundred words to make three hundred and twenty-one questions.
【解决方案2】:
这只是查找文件中存在的数字,如果您不知道如何替换,请使用字典。
import re
text = open('text_numbers.txt')
for line in text:
line = line.strip()
y = re.findall('([0-9]+)',line)
【解决方案3】:
您可以使用正则表达式找到数字,然后您可以使用 num2words 包将数字转换为单词。并简单地替换它们。
In [1]: from num2words import num2words
In [2]: num2words(54)
Out[2]: u'fifty-four'
In [3]: num2words(8)
Out[3]: u'eight'