使用re.findall()
我已经设法在一个字符串中返回一个regex的多个匹配项。但是,返回的对象是字符串中的匹配项列表。这不是我想要的。
我要用别的东西替换所有的火柴。我尝试使用与在re.sub中类似的语法,这样做:
import json
import re
regex = re.compile('([a-zA-Z]\"[a-zA-Z])', re.S)
filepath = "C:\\Python27\\Customer Stuff\\Austin Tweets.txt"
f = open(filepath, 'r')
myfile = re.findall(regex, '([a-zA-Z]\%[a-zA-Z])', f.read())
print myfile
但是,这会导致以下错误:
Traceback (most recent call last):
File "C:/Python27/Customer Stuff/Austin's Script.py", line 9, in <module>
myfile = re.findall(regex, '([a-zA-Z]\%[a-zA-Z])', f.read())
File "C:\Python27\lib\re.py", line 177, in findall
return _compile(pattern, flags).findall(string)
File "C:\Python27\lib\re.py", line 229, in _compile
bypass_cache = flags & DEBUG
TypeError: unsupported operand type(s) for &: 'str' and 'int'
在最后一点语法中,我需要用原始Python对象中的其他内容替换所有匹配项,有人能帮我吗?
编辑:
根据收到的评论和答案,我尝试将一个regex与另一个regex进行细分:
import json
import re
regex = re.compile('([a-zA-Z]\"[a-zA-Z])', re.S)
regex2 = re.compile('([a-zA-Z]%[a-zA-Z])', re.S)
filepath = "C:\\Python27\\Customer Stuff\\Austin Tweets.txt"
f = open(filepath, 'r')
myfile = f.read()
myfile2 = re.sub(regex, regex2, myfile)
print myfile
这将产生以下错误:
Traceback (most recent call last):
File "C:/Python27/Customer Stuff/Austin's Script.py", line 11, in <module>
myfile2 = re.sub(regex, regex2, myfile)
File "C:\Python27\lib\re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "C:\Python27\lib\re.py", line 273, in _subx
template = _compile_repl(template, pattern)
File "C:\Python27\lib\re.py", line 258, in _compile_repl
p = sre_parse.parse_template(repl, pattern)
File "C:\Python27\lib\sre_parse.py", line 706, in parse_template
s = Tokenizer(source)
File "C:\Python27\lib\sre_parse.py", line 181, in __init__
self.__next()
File "C:\Python27\lib\sre_parse.py", line 183, in __next
if self.index >= len(self.string):
TypeError: object of type '_sre.SRE_Pattern' has no len()
最佳答案
import re
regex = re.compile('([a-zA-Z]\"[a-zA-Z])', re.S)
myfile = 'foo"s bar'
myfile2 = regex.sub(lambda m: m.group().replace('"',"%",1), myfile)
print(myfile2)
关于python - 使用re.findall()替换所有匹配项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32670413/