gpt4 book ai didi

python 正则表达式匹配 "ab"或 "ba"单词

转载 作者:行者123 更新时间:2023-11-28 22:37:43 25 4
gpt4 key购买 nike

我尝试匹配包含字母“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 ~~”方法混为一谈......

最佳答案

要匹配所有带有 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

关于python 正则表达式匹配 "ab"或 "ba"单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36245489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com