【问题标题】:python regex matching "ab" or "ba" wordspython 正则表达式匹配“ab”或“ba”单词
【发布时间】:2016-03-27 08:45:15
【问题描述】:

我尝试匹配包含字母“ab”或“ba”的单词,例如“ab”olition,f“ab”rics,pro“ba”ble。我想出了以下正则表达式:

r"[Aa](?=[Bb])[Bb]|[Bb](?=[Aa])[Aa]"

但它包括以“、(、)、/ ....非字母数字字符开头或结尾的单词。我怎样才能删除它?我只想匹配单词列表。

import sys
import re

word=[]

dict={}

f = open('C:/Python27/brown_half.txt', 'rU')
w = open('C:/Python27/brown_halfout.txt', 'w')

data = f.read()
word = data.split() # word is list

f.close()

for num2 in word:
    match2 = re.findall("\w*(ab|ba)\w*", num2)
    if match2:
        dict[num2] = (dict[num2] + 1) if num2 in dict.keys() else 1

for key2 in sorted(dict.iterkeys()):print "%s: %s" % (key2, dict[key2])
print len(dict.keys())

在这里,我不知道如何将它与第一条评论所说的“re.compile~~”方法混为一谈......

【问题讨论】:

  • 教师应该停止说正则表达式是人类已知问题的解决方案......
  • @KemyLand:这应该是公认的答案:)

标签: python regex


【解决方案1】:

用 ab 或 ba 匹配所有单词(不区分大小写):

import re

text = 'fabh, obar! (Abtt) yybA, kk'
pattern = re.compile(r"(\w*(ab|ba)\w*)", re.IGNORECASE)

# to print all the matches
for match in pattern.finditer(text):
  print match.group(0)

# to print the first match
print pattern.search(text).group(0)

https://regex101.com/r/uH3xM9/1

【讨论】:

  • 这是不区分大小写的还是 sensitive ?...它不会匹配 'Ablotion' !...要使其不区分大小写,请添加 re.IGNORECASE 标志。
  • 我试过你的,但它仍然像这样匹配。 .仍然包括标点符号和特殊字符。前任。 “放弃:1”必不可少:1“可能:1”无法:1(中卫:1 2-baser,:1banker。:1 bankers:2 bankers,:1 bankers。:
  • 有没有办法以 re.search 方法打印第 1 组?
  • re.search 将只返回第一个结果。是你想要的吗?
【解决方案2】:

在这种情况下,正则表达式不是工作的最佳工具。对于这种简单的情况,它们会使事情变得过于复杂。您可以改用 Python 的内置 in 运算符(适用于 Python 2 和 3)...

sentence = "There are no probable situations whereby that may happen, or so it seems since the Abolition."
words = [''.join(filter(lambda x: x.isalpha(), token)) for token in sentence.split()]

for word in words:
    word = word.lower()
    if 'ab' in word or 'ba' in word:
        print('Word "{}" matches pattern!'.format(word))

如您所见,如果在 word 中按原样(即完全正确地)找到字符串 'ab',则 'ab' in word 的计算结果为 True,否则为 False。例如'ba' in 'probable' == True'ab' in 'Abolition' == False。第二行将句子分成单词并取出任何标点符号。 word = word.lower() 在比较之前使 word 小写,因此对于 word = 'Abolition''ab' in word == True

【讨论】:

  • 您的words 是一个字符列表,可能您希望在您的理解列表sentence.split() 中代替?
  • @IronFist:我在发布之前测试了代码,但在写答案时忘记了这一点。感谢您的关注!
【解决方案3】:

我会这样做:

  1. 使用以下两个从不需要的字符中删除字符串 技术,你的选择:

    a - 通过构建翻译词典并使用translate 方法:

    >>> import string
    >>> del_punc = dict.fromkeys(ord(c) for c in string.punctuation)
    s = 'abolition, fabrics, probable, test, case, bank;, halfback 1(ablution).'
    >>> s = s.translate(del_punc)
    >>> print(s)
    'abolition fabrics probable test case bank halfback 1ablution'
    

    b - 使用re.sub 方法:

    >>> import string
    >>> import re
    >>> s = 'abolition, fabrics, probable, test, case, bank;, halfback 1(ablution).'
    >>> s = re.sub(r'[%s]'%string.punctuation, '', s)
    >>> print(s)
    'abolition fabrics probable test case bank halfback 1ablution'
    
  2. 接下来将查找包含“ab”或“ba”的单词:

    a - 拆分空格并查找所需字符串的出现,这是我向您推荐的:

    >>> [x for x in s.split() if 'ab' in x.lower() or 'ba' in x.lower()]
    ['abolition', 'fabrics', 'probable', 'bank', 'halfback', '1ablution']
    

    b - 使用re.finditer 方法:

    >>> pat
    re.compile('\\b.*?(ab|ba).*?\\b', re.IGNORECASE)
    >>> for m in pat.finditer(s):
            print(m.group())
    
    
    abolition
    fabrics
    probable
    test case bank
    halfback
    1ablution
    

【讨论】:

    【解决方案4】:
    string = "your string here"
    lowercase = string.lower()
    if 'ab' in lowercase or 'ba' in lowercase:
        print(true)
    else:
        print(false)
    

    【讨论】:

      【解决方案5】:

      试试这个

      [(),/]*([a-z]|(ba|ab))+[(),/]*
      

      【讨论】:

        猜你喜欢
        • 2019-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-10
        • 2015-12-13
        • 1970-01-01
        相关资源
        最近更新 更多