【问题标题】:Replacing words matching regular expressions in python在python中替换匹配正则表达式的单词
【发布时间】:2015-03-06 21:39:27
【问题描述】:
import re
replacement_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
(r'ain\'t', 'is not'),
(r'(\w+)\'ll', '\g<1> will'),
(r'(\w+)n\'t', '\g<1> not'),
(r'(\w+)\'ve', '\g<1> have'),
(r'(\w+)\'s', '\g<1> is'),
(r'(\w+)\'re', '\g<1> are'),
(r'(\w+)\'d', '\g<1> would')
 ]
class RegexpReplacer(object):

   def __init__(self, patterns=replacement_patterns):
      self.patterns = [(re.compile(regex), repl) for (regex, repl)          
                      in pattern]
   def replace(self, text):
      s = text
      for (pattern, repl) in self.patterns:
          (s, count) = re.subn(pattern, repl, s)
   return s


 rep=RegexpReplacer()
 print rep.replace("can't is a contradicton")

我从 Jacob Perkins 的 Python Text Processing with NLTK 2.0 Cookbook 复制了这段代码

但是我的预期输出是: 不能是矛盾的

实际输出为: can't 是矛盾的

我无法确定 t 中的错误

【问题讨论】:

    标签: python regex output nltk ontology


    【解决方案1】:

    要么使用原始字符串转义引号,但不能同时使用。

    >>> print r'won\'t'
    won\'t
    >>> print 'won\'t'
    won't
    

    或者,如果您更喜欢原始字符串:

    >>> print r"won't"
    won't
    

    【讨论】:

    • 谢谢。但是您的解决方案仅适用于不会,而不适用于不能,我等。
    【解决方案2】:

    您的代码有一些缩进问题和拼写错误 - 我不太确定解释器是如何为您提供任何输出的。在我修复了这些之后,我得到了你预期的输出。

    import re
    replacement_patterns = [
    (r'won\'t', 'will not'),
    (r'can\'t', 'cannot'),
    (r'i\'m', 'i am'),
    (r'ain\'t', 'is not'),
    (r'(\w+)\'ll', '\g<1> will'),
    (r'(\w+)n\'t', '\g<1> not'),
    (r'(\w+)\'ve', '\g<1> have'),
    (r'(\w+)\'s', '\g<1> is'),
    (r'(\w+)\'re', '\g<1> are'),
    (r'(\w+)\'d', '\g<1> would')
     ]
    class RegexpReplacer(object):
    
       def __init__(self, patterns=replacement_patterns):
    
          # Fixed this line - "patterns", not "pattern"
          self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns]
    
       def replace(self, text):
          s = text
          for (pattern, repl) in self.patterns:
              (s, count) = re.subn(pattern, repl, s)
    
          # Fixed indentation here
          return s
    
    
    rep=RegexpReplacer()
    print rep.replace("can't is a contradicton")
    

    【讨论】:

    • 谢谢 :) 你能解释一下这行 (s, count) = re.subn(pattern, repl, s)。更具体地说,(s,count) 是什么意思?
    • @AnkitaPrasad re.subn 返回一个双元素元组 - 第一个元素是进行替换后的结果字符串,第二个元素是进行了多少次替换的计数。在 replace 方法的上下文中,(s, count) = re.subn(... 表示您将返回元组的第一个元素分配给 s(字符串),将返回元组的第二个元素(替换次数)分配给 @987654326 @。由于count 未使用,您可以等效地使用s = re.sub(pattern, repl, s)
    • 非常感谢您的帮助:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    相关资源
    最近更新 更多