【问题标题】:Using Python, what is the best way to replace 7x with just 7 in text strings?使用 Python,用文本字符串中的 7 替换 7x 的最佳方法是什么?
【发布时间】:2019-06-23 05:30:37
【问题描述】:

我对 Python 比较陌生,对 nltk 和正则表达式也很陌生。我已经搜索了指导,但没有弄清楚。我只是想删除文本中整数(应该始终是整数)之后的任何 x 或 X,最终只得到数字。我有代码可以在删除 X 或 x 后执行我需要它执行的操作,所以现在我尝试添加到代码中以从数字中删除 x 或 X,但不是普通文本(下面的退出和矩阵之类的词) .

例如,如果我有一个文本字符串:“这是一个美好的一天,710x 只鸟离开它们的栖息地并飞过头顶。其中 130X 俯冲下来落在草地上,而其中 21X 被 7 名猎人射中。 9x 鸟消失在矩阵中。剩下的 550x 鸟继续飞走。'

我想要这个:

'那是美好的一天,710 只鸟离开了它们的栖息地,飞到了头顶。其中130人俯冲下来落在草地上,其中21人被7名猎人射杀。九只鸟消失在矩阵中。剩下的 550 只鸟继续飞走。'

所以我不知道这是否最好由 regex(正则表达式)或 nltk(自然语言工具包)或只是一些 if 语句以某种方式处理。我从我从中提取文本的 pdf 文件中标记了所有可能超过 20,000 到 30,000 个标记/单词的文本,但我很乐意在仍然是一个巨大的字符串时或在它们被制成标记之后删除那些 x。对我来说无所谓。非常感谢您的帮助...

【问题讨论】:

  • 绝对是在 nltk 上的正则表达式(无需核弹苍蝇)。查找re.sub

标签: python regex nltk


【解决方案1】:

这将 x 与前面的字符是数字的断言相匹配,并将 x 替换为空。

re.sub('(?<=\d)[xX]', '', s)

【讨论】:

  • 非常优雅;太糟糕了,它破坏了4x4,这可能不是 OP 要求的??
  • @DimaTisnek 可以通过使用 (?&lt;=\d)[xX](?!\d) 来修复,以不删除两位数之间的 x。
  • 谢谢大家 - 所有这些答案都非常有帮助。我知道我不应该简单地写感谢,但我还不能投票......所以谢谢大家。现在我需要精通所有这些正则表达式语法......
【解决方案2】:

试试这个。

import re

text = 'It was a beautiful day and 710x birds exited their habitats and flew overhead. 130X of them dove down and landed on the grass while 21X of them were shot by 7 hunters. 9x birds vanished into the matrix. The remaining 550x birds kept flying away.'

re.sub(r'(\d+)[xX]', r'\1', text)

# >>> 'It was a beautiful day and 710 birds exited their habitats and flew overhead. 130 of them dove down and landed on the grass while 21 of them were shot by 7 hunters. 9 birds vanished into the matrix. The remaining 550 birds kept flying away.'

这是什么?

re.sub 是用正则表达式替换。第一个参数是要查找的正则表达式,第二个是要替换的正则表达式。

r'(\d+)[xX]' 是由

\d+ <= 1 or more integer sequence
[xX] <= 1 x or X
() <= keep it to use afterwards

r'\1' 表示首先保留的字符串。

【讨论】:

    【解决方案3】:
    def parseNumeric(data):
      for each in data:
        noX =''
        for i in each:
          if i.isdigit():
            noX+=i
        if noX != '':
          data[data.index(each)]=noX
      return " ".join(str(x) for x in data)
    
    
    
    theData = "It was a beautiful day and 710x birds exited their habitats and flew overhead. 130X of them dove down and landed on the grass while 21X of them were shot by 7 hunters. 9x birds vanished into the matrix. The remaining 550x birds kept flying away."
    
    print("\n BEFORE \n")
    
    print(theData)
    
    print("\n AFTER \n")
    
    print(parseNumeric(theData.split()))
    

    查看DEMO,我知道这不是最好的解决方案,但希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-10-09
      • 2016-06-21
      • 2013-12-26
      • 1970-01-01
      • 2010-10-25
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      相关资源
      最近更新 更多