我有一个代码可以迭代地替换关键字中的特定文本, 问题:当我提供文件作为输入时,我得到错误
编码:(在代码中提供文本时效果很好)
import re, itertools
car = ['skoda', 'audi', 'benz']
text = """
I have a car="mycar"
My friend has a vehicle="myvehicle"
My uncle have a car="mycar"
Second verse same as the first
"""
it = itertools.cycle(car)
newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text)
print newtext
编码:当文件作为输入时
import re, itertools
car = ['skoda', 'audi', 'benz']
with open('ckili.txt','r') as text:
text1=text.readlines()
it = itertools.cycle(keywords2)
newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text1)
with open('ckili.txt','w') as f:
f.write(newtext)
我收到错误:
File "C:\Python27\replmay.py", line 8, in <module>
newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text)
File "C:\Python27\lib\re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
>>>
请帮我把输出写入文件!
答案 0 :(得分:2)
您的追溯与您的代码不符。在您的追溯中,使用text
,这是文件对象。
不是说您的代码也适用于text1
;这是列表,而不是str
。不要使用readlines()
,而是使用read()
:
with open('ckili.txt','r') as fileob:
text = fileob.read()
it = itertools.cycle(keywords2)
newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text)
或单独处理每一行。请注意,我冒昧地改变了名字; text
不是文件对象的最佳名称。
您似乎正在将模块导入交互式解释器。知道模块导入已缓存,您需要在更改后显式重新启动解释器或重新加载模块。