我想用python做一个巨大的查找和替换。
tot11.txt
是一个字符串(有600000个项),我想替换文件1.txt
中的项。
例如tot11.txt
有:
'alba'
,'raim'
而1.txt
看起来是这样的:
'alba':'barba', 'raim':'uva'
。
结果我会得到'barba'
,'uva'
,等等。。。
运行脚本时,会出现以下错误:
Traceback (most recent call last):
File "sort2.py", line 12, in <module>
txt = replace_all(my_text, dic)
File "sort2.py", line 4, in replace_all
for i, j in dic.iteritems():
AttributeError: 'str' object has no attribute 'iteritems'
另外,如果我不使用文本文件,只需在脚本中写入可更改的项,脚本也可以很好地工作。
import sys
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
my_text= open('tot11.txt', 'r').read()
reps = open('1.txt', 'r').read()
txt = replace_all(my_text, reps)
f = open('results.txt', 'w')
sys.stdout = f
print txt
replace_all函数的第二个参数是一个字符串,它来自reps=open('1.txt','r').read()。。。。因此,对字符串对象调用iteritems()失败,因为该函数对于字符串对象不存在。
open('1.txt', 'r').read()
返回的字符串不是dict如果
1.txt
包含:然后可以使用
ast.literal_eval
获取dict:与其使用
str.replace
,不如使用regex
,因为str.replace('alba','barba')
还可以替换诸如'albaa'
、'balba'
等词:你不需要用字面上的评价。 这是你的档案:
这是读入字典的代码。正如Ashwini Chaudhary所说,您得到这个错误是因为读取
read()
返回一个字符串。字符串没有名为iteritems
的方法。当然,这假设您的文件中每行只有1
:
。相关问题 更多 >
编程相关推荐