我 在SO之前看过类似的问题(here,here),我知道re.sub
需要一个字符串(我相信,我提供的)但我不知道以下代码中的错误:
tuples = re.findall(r'id":"(.*?)".*?name":"(.*?)"', response.text, re.DOTALL)
outfile = open("badEXtsWithIDs.csv", "wb")
print "Writing into CSV"
writer = csv.writer(outfile)
for entry in tuples:
writeName = re.sub(r'\W', " ", entry)
writer.writerow(writeName)
我认为re.sub
需要一个str
变量,但不是str
的入口吗?我在TypeError: expected string or buffer
的行上收到错误:re.sub
。任何帮助表示赞赏。
答案 0 :(得分:5)
当您有多个匹配组时,re.findall
会返回list
个n - tuple
s:
re.findall('(foo).(bar)', 'foo foo bar foo|bar')
Out[5]: [('foo', 'bar'), ('foo', 'bar')]
很清楚entry
中的每个tuples
都是tuple
。当您将tuple
传递给re.sub
时,它会抱怨。
tuples = re.findall('(foo).(bar)', 'foo foo bar foo|bar')
for entry in tuples:
re.sub('oo','ox',entry)
...
/usr/lib/python3.3/re.py in sub(pattern, repl, string, count, flags)
168 a callable, it's passed the match object and must return
169 a replacement string to be used."""
--> 170 return _compile(pattern, flags).sub(repl, string, count)
171
172 def subn(pattern, repl, string, count=0, flags=0):
TypeError: expected string or buffer
所以,做点别的。也许使用map
:
for entry in tuples:
print(' '.join(map(lambda s: re.sub('oo','ox',s),entry)))
fox bar
fox bar
或者更可读的理解
writer.writerow([re.sub(r'\W', " ",s) for s in entry])
等