【问题标题】:Search and replace numbers with words in file [duplicate]用文件中的单词搜索和替换数字[重复]
【发布时间】:2017-02-23 17:01:51
【问题描述】:

我有一个包含数字和字母的文件,我想将所有数字替换为单词(例如,将 8 转换为 8)。好吧,我只是没有办法检查我的文件中是否有数字。最有效的方法是什么?

【问题讨论】:

  • 您可以创建字典{1: "one", 2: "two"...} 并使用following answer
  • “最有效的方法”取决于很多事情。

标签: 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'
      

      【讨论】:

        【解决方案4】:

        这里也回答了这个问题:replacing text in a file with Python

        如果你想讨论内存用户和其他话题,这个问题应该可以解决问题:Search for string in txt file Python

        有些人解释了从文件中读取文本的不同功能的不同用法,但在你的情况下,它看起来不是一个巨大的文件,所以第一个链接应该会给你答案。

        请记住,当您解析 txt 文件时,即使“8”也是字符串。

        【讨论】:

          猜你喜欢
          • 2011-09-25
          • 2011-09-13
          • 2012-04-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多