搜索并用文件中的单词替换数字[重复]

问题描述 投票:0回答:3

以下内容应奏效,它读取输入文件,使用正则拨号来查找所有数字,而
python regex file search replace
3个回答
12
投票
库则用文本替换为:

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
投票
此处也回答了这个问题:

用python

取代文件中的文本

如果您想讨论内存用户和其他主题,此问题应该可以解决:

1
投票

有些人解释了不同函数的不同用法以读取文件的文本,但是在您的情况下,它似乎不是一个巨大的文件,因此第一个链接应该给您答案。 仅记住,当您解析txt文件时,即使是“ 8”是字符串。

您使用REGEX找到数字,然后可以使用使用num2words

软件包将数字转换为单词。并简单地替换它们。

import re text = open('text_numbers.txt') for line in text: line = line.strip() y = re.findall('([0-9]+)',line)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.