使用re.findall()
我設法返回字符串中正則表達式的多個匹配。然而,我返回的對象是字符串內的匹配列表。這不是我想要的。使用re.findall()替換所有匹配()
我想要的是用其他東西替換所有匹配。我試着使用類似的語法,你會在應用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對象內的其他東西替換所有匹配的語法?
編輯:
在符合意見和答案好評,這裏我想再轉一個正則表達式與另一:
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()
如果要替換匹配項,請使用're.sub'。 –
如何以及在哪裏使用re.sub()雖然?如果你嘗試在你從re.findall()創建的對象上使用它,這是一個匹配列表,而不是原始對象。 – gdogg371
你想用什麼來代替它? –